令operator=返回一个reference to *this.以实现连锁赋值(右结合形式的连锁赋值,不返回reference也可以实现,但每次赋值之后函数返回的时候,会额外调用拷贝构造来创建一个临时的对象)
class Int {
public:
Int() : value(0){}
Int(int i) : value(i) {}
Int(const Int& i):value(i.value) {
cout << "copy constructor." << endl;
}
Int& operator=(const Int &i){
cout << "copy assignment." << endl;
value = i.value;
return *this;
}
void printValue(){
cout << value << endl;
}
private:
int value;
};
int main(int argc, char *args[])
{
Int i;
Int j(1);
Int k(2);
i = j = k;
i.printValue();
j.printValue();
k.printValue();
system("pause");
return 0;
}
运行结果:
copy assignment.
copy assignment.
2
2
2
返回值Int去掉&之后,运行结果为:
copy assignment.
copy constructor.
copy assignment.
copy constructor.
2
2
2