[英]How can I initialize normal array member variable in initializer list?
I would like to do the following: 我要执行以下操作:
class MyClass {
public:
MyClass() : arr({1,2,3,4,5,6,7,8}) {}
private:
uint32_t arr[8];
};
but it doesn't work (compiler: expected primary expression before '}' token.). 但它不起作用(编译器:“}”标记之前的预期主表达式。)。 I've looked at other SO questions and people were passing around things like std::initializer_list
, and trying interesting things like placing the array initializer in double braces like so: 我看过其他SO问题,人们绕过了诸如std::initializer_list
类的东西,并尝试了一些有趣的事情,例如将数组初始化器放在双括号中,例如:
MyClass() : arr( {{1,2,3,4,5,6,7,8}} ) {}
but I'm unfamiliar with the purpose of std::initializer_list
and also I'm not quite sure why there's double braces in the above code (though it doesn't work anyway, so I'm not sure why it matters). 但是我不了解std::initializer_list
的用途,并且我也不太确定为什么上面的代码中有两个大括号(尽管无论如何还是不起作用,所以我不确定为什么很重要)。
Is there a normal way to achieve initialization of my arr
variable in a constructor initializer list? 有没有一种正常的方法可以在构造函数初始化器列表中实现对arr
变量的初始化?
Your syntax is correct. 您的语法正确。 Alternatively, you can say arr{1,2,3,...}
. 或者,您可以说arr{1,2,3,...}
。
Most likely is that your compiler just doesn't support this construction yet. 最有可能的是您的编译器尚不支持这种构造。 GCC 4.4.3 and 4.6.1 both do (with -std=c++0x
). GCC 4.4.3和4.6.1都可以使用( -std=c++0x
)。
Works perfectly on GCC 4.5.2 with -std=gnu++0x. 在带有-std = gnu ++ 0x的GCC 4.5.2上完美工作。 I get a warning and a freeze with -std=c++98. 我收到警告,并使用-std = c ++ 98冻结。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.