Effective C++ 条约10

Effective C++ 条款10

令operator=返回一个reference to *this

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

什么是连锁形式,如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;
}