2014-10-02 64 views
1

由于C++ 11,可以在类定义中初始化成员变量:如何在类定义中初始化std :: array?

class Foo { 
    int i = 3; 
} 

我知道我可以初始化的std ::数组是这样的:

std::array<float, 3> phis = {1, 2, 3}; 

我该怎么办这在一个类的定义?下面的代码给出了一个错误:

class Foo { 
    std::array<float, 3> phis = {1, 2, 3}; 
} 

GCC 4.9.1:

error: array must be initialized with a brace-enclosed initializer 
std::array<float, 3> phis = {1, 2, 3}; 
            ^error: too many initializers for 'std::array<float, 3ul>' 

回答

3

你需要一个更加大括号,这是不直观。

std::array<float, 3> phis = {{1, 2, 3}}; 
+0

这似乎是诀窍,非常感谢! – 2014-10-02 13:02:25

+0

这并不能解释为什么你可以说'std :: array phis = {1,2,3};'在类定义之外。我也会期待大括号在这里适用(但是我通常对这个问题是错误的)。 – juanchopanza 2014-10-02 13:09:26

+0

@juanchopanza我认为就标准而言您是正确的,请参阅[本主题](http:/ /stackoverflow.com/questions/8192185/using-stdarray-with-initialization-lists)。你*应该*能够使用一套大括号,这是正在解决的GCC问题(AFAIK) – CoryKramer 2014-10-02 13:12:52

相关问题