标签:blog io os sp on 2014 log cti bs
条款10: 令operator= 返回一个reference to *this;
关于赋值,我们可以这样写:
int x,y,x;
x =y = z;
这就是所谓的连续赋值
为了实现“连锁赋值”赋值操作符必须返回一个reference指向操作符的左侧实参。这是我们为class实现赋值操作符时应该遵循的协议:
#include <iostream> using namespace std; class Widget { public: Widget() { cout<<"调用无参构造函数"<<endl; } Widget(const Widget& w) { cout<<"调用拷贝构造函数"<<endl; } ~Widget() { } Widget& operator=(const Widget& rhs) //返回类型是个reference 指向当前对象 { cout<<"Hello"<<endl; return *this; //返回左侧对象 } Widget& operator +=(const Widget& rhs) //这个协议也适用于+=,-=,*=等等 { return *this; } }; int main() { Widget w1; Widget w2; Widget w3; w1 = w2 = w3; return 0; }
上面说赋值操作符必须返回一个reference,我以前也是认为如果要连续操作,就必须返回引用,但是我用返回一个对象试着运行了一下,
程序也会通过,并且在这个operator= 中还能得到一模一样的效果:
经过研究发现,并非一定要返回引用,返回值对象时会增加拷贝构造函数和析构函数的调用,所以一般都是返回引用;
#include <iostream> using namespace std; class Widget { public: Widget() { cout<<"调用无参构造函数"<<endl; } Widget(const Widget& w) { cout<<"调用拷贝构造函数"<<endl; } ~Widget() { } /* Widget& operator=(const Widget& rhs) //返回类型是个reference 指向当前对象 { cout<<"Hello"<<endl; return *this; //返回左侧对象 } */ Widget operator=(const Widget& rhs) { cout<<"Hello"<<endl; return *this; } }; int main() { Widget w1; Widget w2; Widget w3; w1 = w2 = w3; return 0; } /* 1:调用返回引用: 调用无参构造函数 调用无参构造函数 调用无参构造函数 Hello Hello 2:调用返回对象 调用无参构造函数 调用无参构造函数 调用无参构造函数 Hello 调用拷贝构造函数 Hello 调用拷贝构造函数 Press any key to continue */
标签:blog io os sp on 2014 log cti bs
原文地址:http://blog.csdn.net/djb100316878/article/details/41084419