为什么const返回阻止:(a1 = a2)= a3?

问题描述 投票:0回答:1

我不明白为什么将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
}
c++ const assignment-operator chaining
1个回答
2
投票

[计算表达式时:

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值,这是不可能的。

© www.soinside.com 2019 - 2024. All rights reserved.