我的教授说运算符重载<lt;在这里是可选的,但我想知道如何做到这一点,因为我只能在不使用重载的情况下计算出来。
这是我代码中的一个函数:
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);
以访问私人成员。
如果您理解了上一个问题的解决方案,那么理解下面的代码非常容易。唯一的区别是朋友功能的使用,你可以阅读gfg链接。
为了更好地理解,下面给出了完全相同的例子,
#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;
}