c++ - 面向对象 : Method for cout output

标签 c++ cout

我必须创建一个方法,在屏幕上打印所有收集到的数据,这是我的尝试:

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/

相关文章:

c++ - OpenGL 在 Release模式下呈现但不在 Debug模式下呈现

c++ - 试图了解 static_cast 中的预期行为

c++ - 拼接一个短整数的第一个和最后一个 3 位数字?

c++ - 为什么输出的每一行之前都有不必要的空格?

C++ 串联哎呀

c++ - 如何修复此异常?

c++ - 从 C++ 中找到 "~/Library/Application Support"?

c++ - 来自简单程序的奇怪符号

c++ - 如何为代码块中的所有 cout 设置精度?

c++ - cout什么时候刷新?