【发布时间】:2020-04-14 09:28:31
【问题描述】:
这个问题与 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 对象?
【问题讨论】:
标签: c++ operator-overloading constants const-correctness this-pointer