为什么常量返回防止:(A1 = A2) = A3?

why does const return prevent: (a1 = a2) = a3?

本文关键字:A2 A3 A1 返回 常量 为什么      更新时间:2023-10-16

我不明白为什么将const添加到返回类型会阻止(a1 = a2) = a3,正如第 2 行的评论所说。
有人可以为我解释一下吗?

// overloaded assignment operator;
// const return prevents: (a1 = a2) = a3
const Array& Array::operator=(const Array& right) {
if (&right != this) { // avoid self-assignment
// for Arrays of different sizes, deallocate original
// left-side Array, then allocate new left-side Array
if (size != right.size) {
delete[] ptr; // release space
size = right.size; // resize this object
ptr = new int[size]; // create space for Array copy
}
for (size_t i{ 0 }; i < size; ++i) {
ptr[i] = right.ptr[i]; // copy array into object
}
}
return *this; // enables x = y = z, for example
}

计算表达式时:

a1 = a2 = a3

分组从右到左,因此表达式变为:

a1 = (a2 = a3)
//   ^^^^^^^^^ const, but evaluated first, so ok. 

这很好,因为括号表达式产生一个const值,该值可用作operator=的参数。

但是在表达式中:

(a1 = a2) = a3
//^^^^^^^^^ const, but evaluated first, so assigning to the result is not ok.

带括号的表达式再次生成一个const值,但现在您正在尝试分配给一个const值,这是不可能的。