在下面的代码段中不允许在C ++标准中使用`a = b + {1,2}? [英] Where in the C++ Standard is `a = b + {1, 2}` disallowed in the snippet below?
本文介绍了在下面的代码段中不允许在C ++标准中使用`a = b + {1,2}?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
标准中 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复数运算符+(复数lhs,const复数和rhs)
{
lhs + = rhs;
return lhs;
}
int main()
{
complex a {1,1}
complex b {2,-3};
a + = {1,3}; // Ok
a = b + {1,2}; //不编译
}
解决方案
它不被列在N3797§8.5.4[dcl.init.list] / 1(强调我的):
:列表初始化
可以用作变量定义(8.5)中的初始化器
$ b
- 在返回语句(6.6.3)
- 中的新表达式(5.3.4)
- 中作为初始值的 (5.2.1)
- 作为函数参数(5.2.2)
<
- 作为非静态数据成员(9.2)的初始化器
- 作为参数传递给构造函数调用(8.5,5.2.3)
$
强调的项目符号对应于 a + = {1,3; / code>。没有符合加法参数的点。
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
}
解决方案
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.
这篇关于在下面的代码段中不允许在C ++标准中使用`a = b + {1,2}?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文