簡體   English   中英

對於這個朋友重載運算符 function 而不僅僅是 std::cout,std::ostream& out 的目的是什么?

[英]What is the purpose of std::ostream& out for this friend overloaded operator function and not just std::cout?

有人可以為這個朋友重載運算符 function 解釋std::ostream &out的目的嗎? 為什么不在 function 中使用std::cout

friend std::ostream& operator<<(std::ostream& out, const Complex& c) 
{
    out << c.real;
    out << "+i" << c.imag << endl;

    return out;
}

相反,像這樣:

friend operator<<(const Complex& c) 
{ 
    std::cout << c.real;
    std::cout << "+i" << c.imag << endl;
}

因為這樣你可以使用任何ostream作為 output,而不僅僅是std::cout例如std::clog << c;

Displaying the output in a function and returning the output stream to the overloaded friend function have different meanings.

您可以將初始化的std::ostream&傳遞給任何其他ostream& 例如, std::coutstd::clogstd::cerr

請注意,這可以在寫入文件時傳遞給文件 stream 實例,例如std::ofstream 1

另外,在您給出的第二個示例中:

friend operator<<(const Complex &c)

您缺少返回類型。 該程序將無法編譯。 此外,需要兩個 arguments 來重載operator<<


1. 感謝@Pete Becker提供這些重要信息。

這個:

 friend std::ostream & operator << (std::ostream &out, const Complex &c) { out << c.real; out << "+i" << c.imag << endl; return out; }

是在您編寫時調用的 function:

Complex c;
std::cout << c;    // same as: operator<<( std::cout, c);

調用std::cout << c; operator<<的實現內部會很糟糕,因為它會遞歸地調用自己而沒有結束。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM