重载的<< [英] Return value of overloaded <<
问题描述
#include <iostream>
using namespace std;
struct info {
info(int x, int y) : x(x), y(y) {}
int x;
int y;
};
ostream& operator<<(ostream& out, const info &myinfo){
out << myinfo.x << " " << myinfo.y;
return cout;
}
int main() {
info a(1,2);
info b(3,4);
cout << a << " " << b << endl;
}
上述程序的输出似乎很好,即使有运算符<<
。
The output of the above program seems fine even with the incorrect overload of operator <<
.
任何人都可以告诉我这个重载问题的影响是什么?我知道重载函数应该返回 out
而不是 cout
,但是上面的版本如何行为?
Can anyone tell me what is the effect of this overloading problem? I know the overloading function should return out
instead of cout
, but how does the above version behave?
推荐答案
在这种情况下,由于你传递 std :: cout
operator<<
,行为上没有差别。一般来说,你会导致<< b<< std :: endl
以发送到 std:cout
,而您的 a
In this case, since you are passing in std::cout
to the overloaded operator<<
, there is no difference in behavior. Generally, though, you would cause the " " << b << std::endl
to get sent to std:cout
, while your a
would go to whatever you passed in.
例如:
info a(1,2);
info b(3,4);
std::ostringstream ss;
ss << a << " " << b << std::endl;
会导致 a
转到 $
。
这篇关于重载的<<的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!