How to initialize an array in C++ objects

后端 未结 2 1596
南方客
南方客 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.

提交回复
热议问题