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

 
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。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值