How to initialize an array in C++ objects

后端 未结 2 1604
南方客
南方客 2020-12-08 17:27

After reading How to initialize an array in C, in particular:

Don\'t overlook the obvious solution, though:

int myArray[10] = { 5, 5, 5, 5

2条回答
  •  南笙
    南笙 (楼主)
    2020-12-08 18:31

    You need to initialize the array in the constructor initialization list

    #include 
    
    class Something {
    private:
    
    int myArray[10];
    
    public:
    
    Something()
    : myArray { 5, 5, 5, 5, 5, 5, 5, 5, 5, 5 }
    {
    }
    
    int ShowThingy(int what) {
        return myArray[what];
    }
    
    ~Something() {}
    };
    
    int main () {
       Something Thing;
        std::cerr << Thing.ShowThingy(3);
    }
    

    ..\src\Something.cpp:6:51: sorry, unimplemented: non-static data member initializers

    C++11 also adds supports for inline initialization of non-static member variables, but as the above error message states, your compiler has not implemented this yet.

提交回复
热议问题