class MyClass {
public:
...
MyClass & operator=(const MyClass &rhs); // return MyClass&
...
}
为什么不C++ - 为什么operator =返回* this的引用而不是* this的对象?
class MyClass {
public:
...
MyClass operator=(const MyClass &rhs); // return MyClass
...
}
难道它是更有效的参考在这种情况下,返回的原因是什么?
谢谢
// *更新*
我想我找到了关键的原因如下:
int i1, it2, i3;
(i1 = i2) = i3; // i3 will be assigned to i1
如果操作的返回类型=是MyClass的,而不是MyClass的&,那么以下语句不会执行与内部数据类型相同的操作。
MyClass mc1, mc2, mc3;
(mc1 = mc2) = mc3;
通过遵循内置类型使用的规则,它被认为是一种良好的做法。
// *** update ***
#include "stdafx.h"
#include <iostream>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
int i1, i2, i3;
i1 = 0;
i2 = 2;
i3 = 3;
(i1 = i2) = i3;
cout << "i1: " << i1 << endl;
cout << "i2: " << i2 << endl;
cout << "i3: " << i3 << endl;
return 0;
}
// output from VS2010
/*
i1: 3
i2: 2
i3: 3
*/
见本类似的问题:(http://stackoverflow.com/q/2447696/478288) – chrisaycock 2011-04-12 03:47:21
否,'i3'将不会分配[在C++重载赋值运算符] 'i1'。其实这个行为在你的'(i1 = i2)= i3'赋值中是未定义的。 – AnT 2011-04-12 04:34:59
@AndreyT:请参阅我的update2。 – q0987 2011-04-12 18:03:21