我的教授说,<
这是我的代码中的一个函数:
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);
在您的班上访问私人成员。
如果您了解上一个问题this的解决方案,那么了解以下代码非常容易。唯一的区别是使用了朋友功能,您可以通过该功能来阅读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;
}