Where in the C++ Standard is `a = b + {1, 2}` disallowed in the snippet below? [duplicate]

青春壹個敷衍的年華 提交于 2019-12-23 10:09:29

问题


Where in the Standard is a = b + {1, 2} disallowed below?

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
}

回答1:


It is disallowed by not being listed in N3797 §8.5.4 [dcl.init.list]/1 (emphasis mine):

Note: List-initialization can be used

  • as the initializer in a variable definition (8.5)
  • as the initializer in a new expression (5.3.4)
  • in a return statement (6.6.3)
  • as a for-range-initializer (6.5)
  • as a function argument (5.2.2)
  • as a subscript (5.2.1)
  • as an argument to a constructor invocation (8.5, 5.2.3)
  • as an initializer for a non-static data member (9.2)
  • in a mem-initializer (12.6.2)
  • on the right-hand side of an assignment (5.17)

The emphasized bullet point corresponds to your a += {1, 3};. There is no point that fits an addition argument.



来源:https://stackoverflow.com/questions/28461022/where-in-the-c-standard-is-a-b-1-2-disallowed-in-the-snippet-below

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!