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;
- }
//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如
请记住:
令赋值(assignment)操作符返回一个reference to *this。