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

时间:2014-05-25 13:33:44   收藏:0   阅读:286

本文为senlie原创,转载请保留此地址:http://blog.csdn.net/zhengsenlie


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

示例:

#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)的赋值操作


Effective C++ Item 10 令operator= 返回一个reference to *this,布布扣,bubuko.com

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!