我必须创建一个方法,在屏幕上打印所有收集到的数据,这是我的尝试:
bool UnPackedFood::printer() {
cout << " -- Unpacked Products --" << endl;
cout << "barcode: " << getBarcode() << endl;
cout << "product name: " << getBezeichnung() << endl << endl;
cout << "weight: " << getGewicht() << endl;
cout << "price" << getKilopreis() << endl;
return true;
}
主要是:
UnPackedFood upf;
cout << upf.printer();
这向我显示了正确的输出,但它仍然返回一个 bool 值,我实际上并不需要它。我试图将该方法声明为无效,但那不起作用。
最佳答案
你应该重载 <<
输出流的运算符。然后当你输入 cout << upf
它将打印您的产品。
看看this example并尝试执行类似于以下代码段的操作:
class UnPackedFood {
...
public:
...
friend ostream & operator<< (ostream &out, const UnPackedFood &p);
};
ostream & operator<< (ostream &out, const UnPackedFood &p) {
out << " -- Unpacked Products --" << endl;
out << "barcode: " << p.getBarcode() << endl;
out << "product name: " << p.getBezeichnung() << endl << endl;
out << "weight: " << p.getGewicht() << endl;
out << "price" << p.getKilopreis() << endl;
return out;
}
关于c++ - 面向对象 : Method for cout output,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32628926/