在 C++ 标准中,下面的代码片段中不允许使用 `a = b + {1, 2}`?
Where in the C++ Standard is `a = b + {1, 2}` disallowed in the snippet below?
标准中的哪个地方 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
}
由于未在 N3797 §8.5.4 [dcl.init.list]/1(强调我的)中列出而被禁止:
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)
强调的要点与您的 a += {1, 3};
相对应。没有符合加法论点的点。
标准中的哪个地方 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
}
由于未在 N3797 §8.5.4 [dcl.init.list]/1(强调我的)中列出而被禁止:
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)
强调的要点与您的 a += {1, 3};
相对应。没有符合加法论点的点。