OOP:用于计数输出的方法

OOP: Method for cout output

本文关键字:输出 方法 用于 OOP      更新时间:2023-10-16

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

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;
}
In my main:
UnPackedFood upf;
cout << upf.printer();

这显示了正确的输出,但它仍然返回给我一个bool值,这实际上是我不需要的。

您应该重载输出流的<<操作符。然后,当您输入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;