C++ OOP:cout输出的方法

C++ OOP:cout输出的方法,c++,cout,C++,Cout,我必须创建一个方法,在屏幕上打印所有收集的数据,下面是我的尝试: bool UnPackedFood::printer() { cout << " -- Unpacked Products --" << endl; cout << "barcode: " << getBarcode() << endl; cout << "product name: " << g

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

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;
}
bool unpacketfood::printer(){

cout三种可能的解决方案:


  • 不要做
    cout三种可能的解决方案:


  • 不要做
    cout你应该重载
    你应该重载
    我不建议构建一个字符串。相反,我建议传递一个流。这样你可以使用
    upf.printer(cout);
    或:
    stringsteam s;upf.printer(s);
    并使用
    s.str()
    将字符串用于其他方式。@JArkinstall如果您将其作为一个字符串发布,这将是一个值得向上投票的答案(当然比注释更完整一点).:)@JArkinstall这是第四种可能的解决方案。虽然在这种情况下,我更倾向于在我的答案中使用备选方案3.:)我同意-重载
    我不建议构建字符串。相反,我建议传递流。这样你可以使用
    upf.printer(cout);
    或:
    strings;upf.printer(s);
    并使用
    s.str()
    将字符串用于其他方式。@JArkinstall如果您将其作为一个字符串发布,这将是一个值得向上投票的答案(当然比注释更完整一点).:)@JArkinstall这是第四种可能的解决方案。虽然在这种情况下,我更倾向于在我的答案中使用备选方案3.:)我同意-重载
    您是否尝试过
    upf.printer();
    而不是
    您是否可以尝试
    upf.printer();
    而不是
    我是否可以在方法打印机()中使用此选项,因为任务是在方法打印机()中打印产品。在这种情况下,只需从
    printer()
    返回
    string
    ,或者不要将当前实现与
    cout
    一起使用。我能够在方法打印机()中使用它,因为任务是在方法打印机()中打印产品。在这种情况下,只需从
    printer()
    返回
    string
    ,或者不要将当前实现用于
    cout
    UnPackedFood upf;
    cout << upf.printer();
    
    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;
    }