运算符<<超载ostream
问题描述:
为了使用cout,std :: cout<< myObject,为什么我必须传递一个ostream对象?我认为这是一个隐含的参数。
In order to use cout as such : std::cout << myObject, why do I have to pass an ostream object? I thought that was an implicit parameter.
ostream &operator<<(ostream &out, const myClass &o) {
out << o.fname << " " << o.lname;
return out;
}
感谢
答
您不是向 ostream
添加另一个成员函数,因为这将需要重新定义类。您不能将它添加到 myClass
,因为 ostream
先行。你唯一可以做的是添加一个重载到一个独立的函数,这是你在做的例子。
You aren't adding another member function to ostream
, since that would require redefining the class. You can't add it to myClass
, since the ostream
goes first. The only thing you can do is add an overload to an independent function, which is what you're doing in the example.