【问题标题】:why does const return prevent: (a1 = a2) = a3?为什么 const return 会阻止:(a1 = a2) = a3?
【发布时间】:2020-09-16 10:09:22
【问题描述】:

我不明白为什么将 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
}

【问题讨论】:

  • 返回类型为const Array&amp;const 使您无法链接分配(您如何分配给const 的东西?)。
  • 返回一个左值引用 Array&amp; 不带 const
  • “避免”是什么意思?

标签: c++ constants assignment-operator chaining


【解决方案1】:

评估表达式时:

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

【讨论】:

  • 好吧,如果赋值运算符是 const 限定的,那么从技术上讲,赋值给 const 值是可行的。但这只是愚蠢的:)
  • 哈哈,没错,语法有效,但毫无意义。或积极混淆。
猜你喜欢
  • 2020-07-09
  • 1970-01-01
  • 1970-01-01
  • 2023-01-09
  • 1970-01-01
  • 2018-08-03
  • 1970-01-01
  • 1970-01-01
  • 2020-08-07
相关资源
最近更新 更多