本文为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)的赋值操作