How can I initialize normal array member variable

2020-02-07 05:35发布

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?

标签: c++ stl
2条回答
爱情/是我丢掉的垃圾
2楼-- · 2020-02-07 06:16

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).

查看更多
仙女界的扛把子
3楼-- · 2020-02-07 06:26

Works perfectly on GCC 4.5.2 with -std=gnu++0x. I get a warning and a freeze with -std=c++98.

查看更多
登录 后发表回答