在下面的代码片段中,C++标准中的"a = b + {1,2}"是不允许的?

Ayr*_*osa 5 c++ language-lawyer

a = b + {1, 2}以下禁止在标准中的哪个位置?

class complex {
    double re, im;
public:
    complex(double r, double i) : re{ r }, im{ i } {}
    complex& operator+=(const complex& other) { re += other.re; im += other.im; return *this; }
};

inline complex operator+(complex lhs, const complex& rhs)
{
    lhs += rhs;
    return lhs;
}

int main()
{
    complex a{ 1, 1 };
    complex b{ 2, -3 };
    a += {1, 3};          // Ok
    a = b + {1, 2};       // doesn't compile
}
Run Code Online (Sandbox Code Playgroud)

chr*_*ris 2

由于未在 N3797 \xc2\xa78.5.4 [dcl.init.list]/1 中列出(强调我的),因此不允许这样做:

\n\n
\n

注意:可以使用列表初始化\n

\n\n
    \n
  • 作为变量定义中的初始值设定项 (8.5)
  • \n
  • 作为新表达式中的初始值设定项 (5.3.4)
  • \n
  • 在返回语句中 (6.6.3)
  • \n
  • 作为 for-range-initializer (6.5)
  • \n
  • 作为函数参数 (5.2.2)
  • \n
  • 作为下标 (5.2.1)
  • \n
  • 作为构造函数调用的参数(8.5、5.2.3)
  • \n
  • 作为非静态数据成员的初始值设定项 (9.2)
  • \n
  • 在内存初始化程序中(12.6.2)
  • \n
  • 在作业的右侧 (5.17)
  • \n
\n
\n\n

强调的要点对应于您的a += {1, 3};. 没有任何点适合加法论证。

\n

  • 未在非规范性注释中列出的不属于规范性内容。 (4认同)