Initialize a constant sized array in an initializer list

前端 未结 3 612
心在旅途
心在旅途 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:35

    "I understand that Set is just a pointer to the static array of 10 integers"

    No, that's wrong: it's an array, not a pointer.

    You can still initialize it in the constructor's initializer list.

    For a compiler that doesn't support C++11 curly braces initialization (Visual C++ version 11 and earlier comes to mind) you'll have to jump through some hoops though, as shown below:

    #include 
    #include 
    using namespace std;
    
    #define CPP11
    #if defined( _MSC_VER )
    #   if (_MSC_VER <= 1700)
    #       undef CPP11
    #   endif
    #endif
    
    #ifdef CPP11
    class Cpp11
    {
    private:
        int set_[10];
    
    public:
        Cpp11()
            : set_{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }
        {}
    
        int foo() const { return set_[3]; }
    };
    #endif
    
    class Cpp03
    {
    private:
        struct IntArray10 { int values[10]; };
        IntArray10 set_;
    
        static IntArray10 const& oneToTen()
        {
            static IntArray10 const values =
                { {1, 2, 3, 4, 5, 6, 7, 8, 9, 10} };
            return values;
        }
    
    public:
        Cpp03()
            : set_( oneToTen() )
        {}
    
        int foo() const { return set_.values[3]; }
    };
    
    int main()
    {}
    

    Instead of using raw arrays, though, use std::vector and C+++11 std::array, both of which are supported even by Visual C++ 11.

提交回复
热议问题