C ++ operator =返回引用* this [英] C++ operator= return reference to *this

查看:130
本文介绍了C ++ operator =返回引用* this的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

查看以下代码:

  #include< iostream> 
using namespace std;

class Widet {
public:
Widet(int val = 0):value(val)
{

} $ b b
Widet& operator =(Widet& rhs)
{
value = rhs.value;
return * this;
}
int getValue()
{
返回值;
}
private:
int value;
};

int main()
{
Widet obj1(1);
Widet obj2(2);
Widet obj3(0);
(obj3 = obj2)= obj1;
cout<< obj3 =< obj3.getValue()<< endl
}

代码成功运行,输出为(使用VS2008):



>



当我让运算符=返回一个值而不是引用:

  Widet operator = ; rhs)
{
value = rhs.value;
return * this;
}

它也会成功运行,输出是:





我的问题是:为什么第二个代码运行良好?我们不应该得到一个错误?



为什么是一个好习惯返回引用* * this?

解决方案


为什么第二个代码运行良好? / p>

因为它是完全有效的代码。它返回对象的临时副本,并且允许在临时对象上调用成员函数(包括 operator =()),因此没有错误。 p>

如果对象不可复制,您会收到错误。


为什么是好习惯返回引用* this而不是* this?


因为不是所有的对象都是可复制的, 。你可以引用任何对象,引用总是很便宜的。


Look at the following code:

#include <iostream>
using namespace std;

class Widet{
public:
    Widet(int val = 0):value(val)
    {

    }

    Widet& operator=(Widet &rhs)
    {
        value = rhs.value;
        return *this;
    }
    int getValue()
    {
        return value;
    }
private:
    int value;
};

int main()
{
    Widet obj1(1);
    Widet obj2(2);
    Widet obj3(0);
    (obj3 = obj2) = obj1;
    cout << "obj3 = " << obj3.getValue() << endl;
}

The code runs successfully and the output is (using VS2008):

When I let the operator= return a value instead of reference:

Widet operator=(Widet &rhs)
{
    value = rhs.value;
    return *this;
}

It also runs successfully and the output is :

My question is :Why the second code runs well?Should not we get a error?

Why it is a good habit to return reference to *this instead of *this?

解决方案

Why the second code runs well?Should not we get a error?

Because it's perfectly valid code. It returns a temporary copy of the object, and you're allowed to call member functions (including operator=()) on temporary objects, so there is no error.

You would get an error if the object were uncopyable.

Why it is a good habit to return reference to *this instead of *this?

Because not all objects are copyable, and some objects are expensive to copy. You can take a reference to any object, and references are always cheap to pass around.

这篇关于C ++ operator =返回引用* this的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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