Initialize a constant sized array in an initializer list

前端 未结 3 709
心在旅途
心在旅途 2021-02-05 05:00

I\'ve got a situation which can be summarized in the following:

class Test
{

    Test();

    int MySet[10];

};

is it possible to initialize

3条回答
  •  刺人心
    刺人心 (楼主)
    2021-02-05 05:34

    While not available in C++03, C++11 introduces extended initializer lists. You can indeed do it if using a compiler compliant with the C++11 standard.

    struct Test {
        Test() : set { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 } { };
        int set[10];
    };
    

    The above code compiles fine using g++ -std=c++0x -c test.cc.


    As pointed out below me by a helpful user in the comments, this code does not compile using Microsoft's VC++ compiler, cl. Perhaps someone can tell me if the equivalent using std::array will?

    #include 
    
    struct Test {
      Test() : set { { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 } } { };
      std::array set;
    };
    

    This also compiles fine using g++ -std=c++0x -c test.cc.

提交回复
热议问题