[英]What is the purpose of std::ostream& out for this friend overloaded operator function and not just std::cout?
Can someone explain the purpose of std::ostream &out
for this friend overloaded operator function?有人可以为这个朋友重载运算符 function 解释
std::ostream &out
的目的吗? Why not just use std::cout
inside the function?为什么不在 function 中使用
std::cout
?
friend std::ostream& operator<<(std::ostream& out, const Complex& c)
{
out << c.real;
out << "+i" << c.imag << endl;
return out;
}
Instead, like so:相反,像这样:
friend operator<<(const Complex& c)
{
std::cout << c.real;
std::cout << "+i" << c.imag << endl;
}
Because this way you can use any ostream
as output, not just std::cout
for example, std::clog << c;
因为这样你可以使用任何
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. Displaying the output in a function and returning the output stream to the overloaded friend function have different meanings.
You can pass the initialized std::ostream&
to any other ostream&
.您可以将初始化的
std::ostream&
传递给任何其他ostream&
。 For example, std::cout
, std::clog
, std::cerr
.例如,
std::cout
、 std::clog
、 std::cerr
。
Note that this can be passed to the file stream instances such as std::ofstream
when writing to a file.请注意,这可以在写入文件时传递给文件 stream 实例,例如
std::ofstream
。 1 1
Also, in your second given example:另外,在您给出的第二个示例中:
friend operator<<(const Complex &c)
You are missing a return type.您缺少返回类型。 The program will fail to compile.
该程序将无法编译。 Also, two arguments are required to overload the
operator<<
.此外,需要两个 arguments 来重载
operator<<
。
1. Thanks to @Pete Becker for suggesting this important information. 1. 感谢@Pete Becker提供这些重要信息。
This:这个:
friend std::ostream & operator << (std::ostream &out, const Complex &c) { out << c.real; out << "+i" << c.imag << endl; return out; }
is the function that gets called when you write:是在您编写时调用的 function:
Complex c;
std::cout << c; // same as: operator<<( std::cout, c);
Calling std::cout << c;
调用
std::cout << c;
inside the implementation of operator<<
would be bad, because then it would call itself recursively with no end.在
operator<<
的实现内部会很糟糕,因为它会递归地调用自己而没有结束。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.