输出流重载
friend ostream& operator<<(ostream& os, MyClass& obj);
我有几个问题:
1. 为什么我需要写“朋友”?
2.为什么要写“&”在“operator”、“os”和“obj”之前?
friend ostream& operator<<(ostream& os, MyClass& obj);
I have e few questions:
1. Why do I need to write 'friend'?
2. Why do I need to write '&' before 'operator', 'os' and 'obj'?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
<强>。为什么我需要写“friend”?
ostream
更改左侧参数(改变流的状态),因此根据一般运算符重载语义,它应该实现为左操作数类型的成员。但是,它的左操作数是来自标准库的流,当您为自己的类型实现输出和输入操作时,您无法更改标准库的流类型。这就是为什么您需要为您自己的类型实现这些运算符作为非成员函数。. Why do I need to write 'friend'?
ostream
changes the left argument(alters the stream’s state), and hence as per general operator overloading semantics it should be implemented as member of left operand type. However, its left operand is a stream from the standard library, when you implement the output and input operations for your own type, you cannot change the standard library’s stream types. That’s why you need to implement these operators for your own types as non-member functions.MyClass&
中的&
使函数采用对 MyClass 对象的引用,而不是对象本身。 (其他的也类似。)引用是轻量级的,可以轻松传递,并且对
obj
所做的任何更改都会影响原始对象。如果没有&
,您将指示编译器在调用中构造一个全新的MyClass
,在返回时销毁它,并丢弃您可能对其内部所做的任何更改状态。ostream&
的返回通常用于返回相同的 ostream& 。这是传入的,因此您可以编写诸如cout << 之类的移位链“你好”<<第42话endl;
并让它们按照您期望的方式运行。 (你可以让它返回不同的东西 - C++ 很容易完全扰乱人们的期望 - 但不要这样做。)The
&
inMyClass&
makes the function take a reference to a MyClass object, not the object itself. (Similarly for the others.)References are lightweight to pass around, and any change you make to the
obj
affects the original object. Without the&
you would be instructing the compiler to construct a whole newMyClass
in the call, destroy it on return and throw away any changes you might have made to its internal state.The return of an
ostream&
is conventionally used to return the same ostream& that was passed in so you can write chains of shifts likecout << "hello " << 42 << endl;
and have them behave the way you expect. (You could have it return something different - C++ makes it easy to completely mess with people's expectations - but don't do that.)