现在的位置: 首页 > 综合 > 正文

Effective c++学习笔记——条款10:令operator=返回一个*this的引用

2013年12月04日 ⁄ 综合 ⁄ 共 2046字 ⁄ 字号 评论关闭

 

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所遵循的协议。
下面看一个实际例子;

  1. // have_assi.cpp : 定义控制台应用程序的入口点。
      
  2.   
  3. //2011/9/10 by wallwind on sunrise
      
  4.   
  5.   
  6. #include "stdafx.h"   
  7.   
  8. #include <iostream>   
  9.   
  10. using namespace std;  
  11.   
  12.   
  13. class Widget  
  14.   
  15. {  
  16.   
  17. public:  
  18.   
  19.     Widget():i(0){}  
  20.   
  21.     Widget(int ii):i(ii){}  
  22.   
  23.     Widget& operator=(const Widget &rhs)  
  24.   
  25.     {  
  26.   
  27.         this->setValue(rhs.getValue());  
  28.   
  29.         return *this;  
  30.   
  31.     }  
  32.   
  33.       
  34.   
  35.     Widget& operator+=(const Widget& rhs)   
  36.   
  37.     {  
  38.   
  39.         this->setValue(rhs.getValue() + this->getValue());  
  40.   
  41.         return *this;  
  42.   
  43.     }  
  44.   
  45.   
  46.     int getValue() const {return i;}  
  47.   
  48.     void setValue(int ii){i=ii;}  
  49.   
  50. private:  
  51.   
  52.     int i;  
  53.   
  54. };  
  55.   
  56.   
  57. int _tmain(int argc, _TCHAR* argv[])  
  58.   
  59. {  
  60.   
  61.     Widget w1,w2,w3;  
  62.   
  63.     w1=w2=w3=10;  
  64.   
  65.     cout<<w1.getValue()<<endl;  
  66.   
  67.     cout<<w2.getValue()<<endl;  
  68.   
  69.     cout<<w3.getValue()<<endl;  
  70.   
  71.     w1+=10;  
  72.   
  73.     w2+=20;  
  74.   
  75.     w3+=30;  
  76.   
  77.     cout<<w1.getValue()<<endl;  
  78.   
  79.     cout<<w2.getValue()<<endl;  
  80.   
  81.     cout<<w3.getValue()<<endl;  
  82.   
  83.   
  84.     return 0;  
  85.   
  86. }  

输出结果,如图所示
 

如书中所说,这只是个协议,并我强制性,如果不遵守,代码一样可以通过他编译。然而c++的内置类型,和stl如

string vector 等都遵守这个协议。所以,你最好按这个做吧。

请记住:

令赋值(assignment)操作符返回一个reference to *this。

抱歉!评论已关闭.