运算符<<重载ostream
为了这样使用 cout : std::cout << myObject,为什么我必须传递 ostream 对象?我认为这是一个隐式参数。
ostream &operator<<(ostream &out, const myClass &o) {
out << o.fname << " " << o.lname;
return out;
}
谢谢
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您不会向
ostream
添加另一个成员函数,因为这需要重新定义该类。您无法将其添加到myClass
中,因为ostream
首先出现。您唯一能做的就是向独立函数添加重载,这就是您在示例中所做的。You aren't adding another member function to
ostream
, since that would require redefining the class. You can't add it tomyClass
, since theostream
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.仅当它是类的成员函数时才会成为第一个参数。因此,它会是:
由于
ostream
是在您的课程之前很久编写的,因此您会看到将您的课程放在那里的问题。因此,我们必须将运算符实现为独立函数:当运算符实现为类的成员函数时,左侧是
this
,参数变为右侧。 (对于二元运算符 - 一元运算符的工作原理类似。)Only if it is a member function of the class that would otherwise be the first argument. Thus, it would be:
Since
ostream
was written long before your class, you see the problem of getting your class in there. Thus, we must implement the operator as a freestanding function:When operators are implemented as member-functions of classes, the left hand side is
this
, and the argument becomes the right hand side. (For binary operators - unary operators work similarly.)因为您正在重载自由函数,而不是成员函数。
Because you are overloading a free function, not a member function.