就地成员初始化和聚合初始化 [英] In place member initialization and aggregate initialization
问题描述
我有这个简单的结构和一个函数:
I have this simple struct and a function taking it:
struct S
{
int a;
};
void foo(S){}
foo({5});
这很好。
我将 int a; 更改为
int a {0};
VisualStudio(2013年和2015年)抱怨:
But if I change int a;
to int a{0};
VisualStudio (2013 and 2015) complains:
error C2664: 'void foo(S)': cannot convert argument 1 from 'initializer list' to 'S'
在文档中找不到相应的规则。但 gcc
和 clang
接受这个没有问题。
I can't find corresponding rule for this in the documentation. But both gcc
and clang
accept this without problem.
推荐答案
struct S
{
int a;
};
是汇总
,而
struct S
{
int a {0}; // or int a = 0;
};
在c ++ 11中不是聚合,而是在c ++ 14中。
is not an aggregate in c++11, but is in c++14.
VisualStudio(2013和2015)在这方面仍使用c ++ 11规则。
VisualStudio (2013 and 2015) still uses the c++11 rules in this regard.
foo({5});
对聚合有效。对于非聚合,它将(尝试)调用适当的构造函数,但 S
没有此参数的有效值。
foo({5});
is valid for aggregate. For non aggregate, it will (try to) call appropriate constructor, but S
doesn't have one valid for this argument.
这篇关于就地成员初始化和聚合初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!