标签:
赋值操作为什么要返回 reference to *this? 要弄清这个问题之前,先了解函数的返回值类型:返回值类型,返回引用类型
test operator= (const test &t){...cout << "赋值" << endl;return *this;}
test &operator= (const test &t){...cout << "赋值" << endl;return *this;}
class test{public:test() :i(10){cout << "构造" << endl;}~test(){}test(const test &t){this->i = t.i;cout << "拷贝" << endl;}test operator= (const test &t){i = t.i;cout << "赋值" << endl;return *this;}void setData(int value){i = value;}int getData(){return i;}private:int i;};int _tmain(int argc, _TCHAR* argv[]){test a;test b;test c;cout << a.getData() << endl << b.getData() << endl<<c.getData() << endl;a.setData(20);c = b= a;cout << a.getData() << endl << b.getData() << endl << c.getData() << endl;return 0;}
,可以看出仅仅是在每次赋值完后多了一次拷贝。现在考虑一个情况
。分析:因为c=b,返回的是一个临时的对象,因此其实最后a赋值给了一个临时变量且多了一次拷贝。
(c=b)=a,对象c被成功赋值,且整个过程少了两次拷贝。C++ 赋值函数为什么返回reference to *this?
标签:
原文地址:http://www.cnblogs.com/chengkeke/p/5417359.html