How to initialize an array in C++ objects

后端 未结 2 1588
南方客
南方客 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:24

    Unless I'm mistaken, the initializer list is only allowed for when the variable is initialized during declaration - hence the name. You can't assign an initializer list to a variable, as you're trying to do in most of your examples.

    In your last example, you're trying to add static initialization to a non-static member. If you want the array to be a static member of the class, you could try something like this:

    class Derp {
    private:
        static int myArray[10];
    }
    
    Derp::myArray[] = { 5, 5, 5, 5, 5, 5, 5, 5, 5, 5 };
    

    If you want to add a class member, you could try making the static array const and copy it into the member array in the constructor.

    0 讨论(0)
  • 2020-12-08 18:31

    You need to initialize the array in the constructor initialization list

    #include <iostream>
    
    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.

    0 讨论(0)
提交回复
热议问题