您的位置:首页 > 编程语言 > C语言/C++

Effective C++ Item 10 令operator= 返回一个reference to *this

2014-10-28 16:42 525 查看
本文为senlie原创,转载请保留此地址:http://blog.csdn.net/zhengsenlie

经验:令赋值(assignment)操作符返回一个reference to *this --》 这样可以实现级联赋值
示例:

[cpp] view
plaincopy





#include <iostream>  

#include <string>  

using namespace std;  

  

class Widget{  

public:  

    Widget(int v):value(v){}  

    Widget& operator=(const Widget &rhs){     

        this->value = rhs.value;  

        return *this; //返回左侧对象  

    }  

    int getValue() const {return this->value;}  

private:  

    int value;  

};  

  

  

int main(){  

    Widget w1(1);  

    Widget w2(2);  

    Widget w3(3);  

    w3 = w2 = w1;  

    cout << w3.getValue() << endl;  

    system("pause");  

}  

输出:

1

解析:

令operator=,opertor+= 返回一个referenceto *this可以实现级联式(casading)的赋值操作
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐