简体   繁体   中英

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:

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?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM