【发布时间】:2020-07-17 10:42:05
【问题描述】:
在赋值运算符重载时,为什么我们返回对对象的引用,为什么它不能返回常量引用?例如,在这种情况下:
MyClass& MyClass::operator=(const MyClass &rhs) {
... // Do the assignment
return *this;
}
为什么我们不能返回像这样的常量引用:
const MyClass& MyClass::operator=(const MyClass &rhs) {
... // Do the assignment operation!
return *this; // Return a reference to myself.
}
【问题讨论】:
-
你可以,但你为什么要呢?
*this在这里是非常量的,为什么要添加常量? -
当然可以,但它有什么好处呢?如果这样做,您将禁止使用
(a = b).NonConstMember();之类的表达式。 -
返回类型可以是
MyClass const&。它甚至可以是void。对于期望(并依赖)更典型行为的人来说,其中任何一个都可能令人惊讶。
标签: c++