繁体   English   中英

OOP:cout输出的方法

[英]OOP: Method for cout output

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

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值,而我实际上并不需要。 我试图将方法声明为void,但这没用。

您应该对输出流重载<<运算符。 然后,当您键入cout << upf ,它将打印您的产品。

看一下此示例 ,尝试执行与以下代码段相似的操作:

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;
}

三种可能的解决方案:

  1. 不要做cout << upf.printer(); ,则不需要输出,因为函数本身可以输出。

  2. 而不是在printer函数中写入输出,而是追加一个字符串并返回该字符串。

  3. UnPackedFood一个重载的operator<< ,这样就可以执行std::cout << upf; UnPackedFood

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM