这是来自 '03 或 '04 的 C++ 筛选测试。
Which of the following declares the assignment operator of MyClass so that the code on Line 3 generates a compilation error while the code on line 2 does not?
Consider the following code fragment:
(Line 1) MyClass a, b, c; (Line 2) a=b=c; (Line 3) (a=b)=c; 1) void operator=( const MyClass& X ); 2) MyClass operator=( const MyClass& X ); 3) const MyClass operator=( const MyClass& X ); 4) None of the above
正确答案是 3)。现在,怎么会这样?它是如何工作的?什么叫什么? parens是否强制创建临时文件? const 如何参与其中?
最佳答案
将赋值重写为函数调用而不是运算符可能会有所帮助(正如其他人明确指出的那样,没有任何 (),赋值从右到左进行):
Line 2: a.operator=(b.operator=(c));
Line 3: (a.operator=(b)).operator=(c);
这使得在第 3 行更清楚一点,您正在尝试获取 a=b
的结果并将 c
分配给它。但在情况 3 中,operator=
的输出是一个 const 对象,因此这是不允许的(因为 operator=
是一个非常量函数)。
将每个赋值分解为两个单独的语句可能会更清楚:
// with const MyClass MyClass::operator=( const MyClass& X );
// line 1
MyClass a, b, c;
//line 2; originally a=b=c
const MyClass d = (b = c);
a = d; // no problem; a is nonconst, and it's ok for d (the parameter to operator=) to be const
//line 3; originally (a=b)=c
const MyClass e = (a = b); // note: the leftmost = here is initialization rather than assignment
e = c; // no good! e is const, and you can't call a nonconst function like operator= on a const object
或者更进一步,通过使用名为 assign
的函数代替 operator=
来消除任何与运算符相关的混淆:
// with const MyClass MyClass::assign( const MyClass& X );
// line 1
MyClass a, b, c;
//line 2; originally a=b=c
const MyClass d = b.assign(c);
a.assign(d); // ok. assign() is nonconst, but so is a.
//line 3; originally (a=b)=c
const MyClass e = a.assign(b);
e.assign(c); // no good! e is const and assign() is not.
关于C++ const重载赋值运算符机制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24416914/