输出流重载

发布于 2024-11-09 18:40:38 字数 177 浏览 0 评论 0原文

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

放我走吧 2024-11-16 18:40:46

<强>。为什么我需要写“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.

饭团 2024-11-16 18:40:45

MyClass& 中的 & 使函数采用对 MyClass 对象的引用,而不是对象本身。 (其他的也类似。)

引用是轻量级的,可以轻松传递,并且对 obj 所做的任何更改都会影响原始对象。如果没有 &,您将指示编译器在调用中构造一个全新的 MyClass,在返回时销毁它,并丢弃您可能对其内部所做的任何更改状态。

ostream& 的返回通常用于返回相同的 ostream& 。这是传入的,因此您可以编写诸如 cout << 之类的移位链“你好”<<第42话endl; 并让它们按照您期望的方式运行。 (你可以让它返回不同的东西 - C++ 很容易完全扰乱人们的期望 - 但不要这样做。)

The & in MyClass& 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 new MyClass 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 like cout << "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.)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文