Have assignment operators return a reference to *this
从题目,我们就要记住这条信息,让你的operator=函数return *this;
基本类型int、char等都提供了连锁赋值,并采用右结合律。
int x, y, z;
x = y = z = 15; 这句真正被解析为:x = (y = (z = 15));
为了实现连锁赋值,赋值操作符必须返回一个引用指向操作符左侧实参,这是通常在C++中为classes所遵循的协议。
int x, y, z;
x = y = z = 15; 这句真正被解析为:x = (y = (z = 15));
为了实现连锁赋值,赋值操作符必须返回一个引用指向操作符左侧实参,这是通常在C++中为classes所遵循的协议。
下面看一个实际例子;
// have_assi.cpp : 定义控制台应用程序的入口点。 //2011/9/10 by wallwind on sunrise #include "stdafx.h" #include <iostream> using namespace std; class Widget { public: Widget():i(0){} Widget(int ii):i(ii){} Widget& operator=(const Widget &rhs) { this->setValue(rhs.getValue()); return *this; } Widget& operator+=(const Widget& rhs) { this->setValue(rhs.getValue() + this->getValue()); return *this; } int getValue() const {return i;} void setValue(int ii){i=ii;} private: int i; }; int _tmain(int argc, _TCHAR* argv[]) { Widget w1,w2,w3; w1=w2=w3=10; cout<<w1.getValue()<<endl; cout<<w2.getValue()<<endl; cout<<w3.getValue()<<endl; w1+=10; w2+=20; w3+=30; cout<<w1.getValue()<<endl; cout<<w2.getValue()<<endl; cout<<w3.getValue()<<endl; return 0; }
输出结果,如图所示
如书中所说,这只是个协议,并我强制性,如果不遵守,代码一样可以通过他编译。然而c++的内置类型,和stl如
string vector 等都遵守这个协议。所以,你最好按这个做吧。
请记住:
令赋值(assignment)操作符返回一个reference to *this。