简体   繁体   English

为什么重载运算符<<必须通过引用返回?

[英]why overloading of operator<< must return by reference?

I want to print out an object of a user-defined type, like this cout << ob1; 我想打印出一个用户定义类型的对象,比如这个cout << ob1; so I want to overload operator<< and I want to return by value not by reference but it gives me an error: in two files named : iosfwd and ios_base.h 所以我想重载operator <<并且我希望按值返回而不是通过引用但是它给了我一个错误:在两个名为的文件中: iosfwdios_base.h

ostream operator<<( ostream& out, cat& rhs){
    out << rhs.a << ", " << rhs.b << endl;
    return out ; 
}

1)Is it because it can't create a new ostream object, this is why it have to return by reference ? 1)是因为它不能创建一个新的ostream对象,这就是为什么它必须通过引用返回?

but when I return by reference like this : 但是当我像这样通过引用返回时:

ostream& operator<<( ostream& out, cat& rhs){
    out << rhs.a << ", " << rhs.b << endl;
    return out ;
}

it works fine. 它工作正常。
2)any explanation ? 2)有什么解释吗?

In the first example, you return a copy of the stream object which is not allowed because the copy-constructors (and copy-assignment as well) of all the stream classes in C++ has been disabled by having them made private . 在第一个示例中,您返回了一个不允许的流对象的副本,因为C ++中所有流类的复制构造函数(以及复制赋值)已被禁用,因为它们是private

Since you cannot make a copy of a stream object, you're required to return it by reference , which you're doing in the second example which is why it is working fine. 由于您无法复制流对象,因此您需要通过引用返回它,您在第二个示例中执行此操作,这就是它工作正常的原因。

You may choose to return nothing at all (ie you can make the return type void ), but if you do so, then you would not be able to chain as stream << a << b . 您可以选择根本不返回任何内容(即,您可以使返回类型为void ),但如果您这样做,那么您将无法链接stream << a << b You've to write them separately as stream <<a and then stream << b . 你要将它们分别写成stream <<a然后stream << b

If you want to know why copying of stream objects is disabled, see my answer here: 如果您想知道为什么禁用复制流对象,请在此处查看我的答案:

Streams are non copyable because copying a stream doesn't really make sense, a stream is unique (you can't jump in the same river twice kind of thing). 流是不可复制的,因为复制流并不真正有意义,流是唯一的(你不能在同一条河中跳两次)。 return by value is in C++03 at least copying transaction. 按值返回是在C ++ 03中至少复制事务。

If there are reason you want to return by value, return by reference is the correct version. 如果有理由要按值返回,则按引用返回的是正确的版本。

It is done to support safe and reasonable operator chaining like 这样做是为了支持安全合理的操作员链接

    cout<<a<<b;  

works because of returning a reference. 因为返回引用而起作用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM