簡體   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