这个问题与重载 C++ 中的赋值运算符有关。看看下面的代码。它显示了我的书给重载赋值运算符的函数定义。
const cAssignmentOprOverload& cAssignmentOprOverload::operator=(
const cAssignmentOprOverload& otherList) {
if (this != &otherList) // avoid self-assignment; Line 1
{
delete[] list; // Line 2
maxSize = otherList.maxSize; // Line 3
length = otherList.length; // Line 4
list = new int[maxSize]; // Line 5
for (int i = 0; i < length; i++) // Line 6
list[i] = otherList.list[i]; // Line 7
}
return *this; // Line 8
}
使这个难以理解的最大问题是在函数的定义中,它返回 *this
。 *this
是一个 const
对象吗?我不认为这是为什么当返回类型应该是 const
时允许我们返回一个非 const
对象?
最佳答案
在非静态成员函数体内,表达式this
可用于获取指向调用该函数的对象的指针[expr.prim.this] .由于您的 operator =
不是 const 成员函数,因此 this
将指向一个非常量对象(这是有道理的,因为我们正在为某物分配一个新值)。因此,*this
将导致 cAssignmentOprOverload
类型的非常量左值。但是,对 const 的引用可以绑定(bind)到非 const 左值 [dcl.init.ref]/5.1.1 .通常,较少 const 限定的类型总是可以隐式转换为更多 const 限定的类型。这是有道理的:您应该能够在非可修改对象就足够的地方使用可修改对象。将可修改的对象视为不可修改的对象不会出错。所发生的只是您丢失了该对象实际上是可修改的信息。恰恰相反,将不可修改的对象视为可修改的对象是有问题的……
请注意,这种编写重载operator =
的方式不是how this is typically done .规范形式是
cAssignmentOprOverload& operator=(const cAssignmentOprOverload& otherList)
即,返回对非常量的引用......
关于c++ - 对象 "this"是否指向与 const 对象相同的对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59449432/