码迷,mamicode.com
首页 > 其他好文 > 详细

operator = 为什么要返回*this的应用

时间:2014-08-07 12:15:49      阅读:173      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   art   ar   问题   cti   

Effictive c++中将要让operator =()返回*this的引用,原因说是为了连环赋值,测试一下,发现不是如此,参考http://blog.csdn.net/nodeathphoenix/article/details/38146421

class Test {
public:
    Test():num(0) {
    }
    Test(int n) :num(n) {
    }
    Test(const Test &test):num(test.num) {
    }
    Test operator =(Test &test) {
        num=test.num;
        return *this;
    }
    void Show(const Test &test) {
        std::cout << num <<std::endl;
        std::cout << test.num << std::endl;
    }
    ~Test() {
    };
private:
    int num;
};

一样可以连环复制,如

Test a,b,c(10);
a=b=c;

结果a,b,c都是10

但是如果

Test a,b,c(10);
(a=b)=c;

a,b都是0了,原因如下:

a=b的函数执行过程中,会创建临时变量,之后再通过copy构造函数构造a,而(a=b)=c其实是把c赋值给临时变量,所以并没有影响到a的值。

如果返回引用,则不存在这个问题,而且少调用了两次copy构造函数,效率也更高。

通过这个我发现,类的成员函数是可以访问类的任何实例的私有变量,如上面的Show(Test &test)函数。因为类的成员函数是跟类绑定在一起的,而不是跟类的实例绑定的。而且,类的成员函数不占用类的实例的空间。

operator = 为什么要返回*this的应用,布布扣,bubuko.com

operator = 为什么要返回*this的应用

标签:style   blog   http   color   art   ar   问题   cti   

原文地址:http://www.cnblogs.com/clark-lee/p/3896537.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!