首页 > 编程语言 > 详细

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

时间:2014-05-25 13:33:11      阅读:388      评论:0      收藏:0      [点我收藏+]

本文为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

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

原文:http://blog.csdn.net/zhengsenlie/article/details/26864447

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!