我将如何操作重载“<<”?

How would I operate overload "<<"?

我的教授说 << 的运算符重载在这里是可选的,但我想知道我该怎么做,因为我只能在不使用重载的情况下弄清楚。

这是我代码中的一个函数:

void listProducts()
{
    //list all the available products.
    cout << "Available products:\n";
    for(int i=0; i<numProducts; i++)
        cout << products[i]->getCode() << ": " << products[i]->getName() << " @ "
             << products[i]->getPrice() << "/pound.\n";
}

这是 product.cpp 文件:

Product :: Product(int code, string name, double price) {
this->code = code;
this->name = name;
this->price = price;
}

int Product:: getCode(){
return code;
}

string Product :: getName(){
return name;
}

double Product :: getPrice(){
return price;
}

你可以做类似

std::ostream & operator<<(std::ostream &out,const classname &outval)
{
    //output operation like out<<outval.code<<":"<<outval.name<<"@"<<outval.price;
    return out;
}

friend std::ostream & operator<<(std::ostream &out,const classname &outval);

在您的 class 中访问私有成员。

如果您理解上一个问题的解决方案, then understanding the below code is very easy. The only difference is the usage of friend function about which you can read gfg link

为了您更好地理解,下面给出了完全相同的示例,

#include <iostream>
using namespace std;

class Product
{
private:
    int code; string name; double price;
public:
    Product(int, string, double);
    friend ostream & operator << (ostream &out, const Product &p);

};

Product :: Product(int code, string name, double price) {
    this->code = code;
    this->name = name;
    this->price = price;
}

ostream & operator << (ostream &out, const Product &p)
{
    out<< p.code << ": " << p.name << " @ "
             << p.price << "/pound.\n";
    return out;
}


int main()
{
   Product book1(1256,"Into to programming", 256.50);
   Product book2(1257,"Into to c++", 230.50);
   cout<<book1<<endl<<book2;
   return 0;
}