如何在初始化列表中初始化普通数组成员变量?
我想执行以下操作:
class MyClass {
public:
MyClass() : arr({1,2,3,4,5,6,7,8}) {}
private:
uint32_t arr[8];
};
但它不起作用(编译器:“}”标记之前预期的主要表达式。)。我看过其他 SO 问题,人们正在传递诸如 std::initializer_list 之类的东西,并尝试有趣的事情,例如将数组初始值设定项放在双括号中,如下所示:
MyClass() : arr( {{1,2,3,4,5,6,7,8}} ) {}
但我不熟悉其目的std::initializer_list
并且我不太确定为什么上面的代码中有双大括号(尽管它无论如何都不起作用,所以我不确定为什么它很重要)。
有没有一种正常的方法可以在构造函数初始值设定项列表中实现我的 arr
变量的初始化?
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:
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).
Is there a normal way to achieve initialization of my arr
variable in a constructor initializer list?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你的语法是正确的。或者,您也可以说
arr{1,2,3,...}
。最有可能的是您的编译器还不支持这种构造。 GCC 4.4.3 和 4.6.1 都这样做(使用
-std=c++0x
)。Your syntax is correct. Alternatively, you can say
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
).在带有 -std=gnu++0x 的 GCC 4.5.2 上完美运行。我收到警告并冻结 -std=c++98。
Works perfectly on GCC 4.5.2 with -std=gnu++0x. I get a warning and a freeze with -std=c++98.