为什么运算符重载<<必须通过引用返回? [英] why overloading of operator&lt;&lt; must return by reference?

查看:89
本文介绍了为什么运算符重载<<必须通过引用返回?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想打印出一个用户定义类型的对象,就像这样 cout <<ob1;所以我想重载 operator<<我想按值而不是按引用返回,但它给了我一个错误:在名为 iosfwdios_base.h

I want to print out an object of a user-defined type, like this 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

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

1)是不是因为它不能创建一个新的ostream对象,这就是它必须通过引用返回的原因?

但是当我像这样通过引用返回时:

but when I return by reference like this :

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

效果很好.
2) 有什么解释吗?

推荐答案

在第一个示例中,您返回流对象的副本,这是不允许的,因为 所有 C++ 中的流类已通过将它们设为 private 来禁用.

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.

由于您无法制作流对象的副本,您需要通过引用返回它,您在第二个示例中正在这样做,这就是它工作正常的原因.

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.

您可以选择不返回任何内容(即您可以将返回类型设为 void),但如果您这样做,您将无法链接作为<代码>流<<<<b.您必须将它们分别编写为 stream <stream <<b.

You may choose to return nothing at all (i.e you can make the return type void), but if you do so, then you would not be able to chain as stream << a << b. You've to write them separately as stream <<a and then stream << b.

如果您想知道为什么禁止复制流对象,请在此处查看我的回答:

If you want to know why copying of stream objects is disabled, see my answer here:

这篇关于为什么运算符重载<<必须通过引用返回?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆