Effective C++ 条款10

令operator=返回一个reference to *this

将operator=返回一个reference是为了什么呢?答案非常easy,就是为了实现连锁形式。

什么是连锁形式。如int x。y,z。x=y=z=15;这样的形式就是连锁形式。

声明一下。这仅仅是个大家一致允许的写法。你也能够不遵守这样的写法。

但是不管是内置类型还是标准库的类型,都遵循这条规则。

为了达到程序的一致性。也是遵守的比較好。

下面是涉及的代码:

#include<iostream>
using namespace std;

class Widget
{

public:
    Widget()
    {
        cout<<"Default Ctor"<<endl;
    }
    Widget(const Widget& rhs)
    {
        cout<<"Copy Ctor"<<endl;
    }
    Widget& operator=(const Widget& rhs)
    {
        cout<<"operator="<<endl;
        return *this;
    }
};
int main()
{
    Widget a,b,c;
    a=b=c;
    return 0;
}
posted @ 2017-06-11 15:03  yjbjingcha  阅读(129)  评论(0)    收藏  举报