Can't specify an explicit initializer for arrays

Why does it compile in VS 2013

int main()
{

    int a[3] = { 1, 2, 3 };

    return 0;

}

      

but this gives error

class TestClass
{

    int a[3] = { 1, 2, 3 };

};

      

How to fix it?

+3


source to share


3 answers


From Bjarne C ++ 11 FAQ page :

In C ++ 98, only static const members of integral types can be initialized in a class, and the initializer must be a constant expression. [...] The basic idea behind C ++ 11 is to allow a non-static data member to be initialized where it is declared (in its class).

The problem is that VS2013 doesn't implement all the features of C ++ 11 and this is one of them. So, I suggest you use std :: array (note the extra set of curly braces):



#include <array>

class A
{
public:
    A() : a({ { 1, 2, 3 } }) {} // This is aggregate initialization, see main() for another example

private:
    std::array<int, 3> a; // This could also be std::vector<int> depending on what you need.
};

int main()
{
    std::array<int, 3> std_ar2 { {1,2,3} };
    A a;

    return 0;
}

      

cppreference to initialize the aggregate

If you're curious, you can click on this link to see that what you were doing will compile when using the compiler that implemented this feature (g ++ in this case, I tried it on clang ++ and it works too).

+9


source


Why: Not yet implemented in this version of Visual C ++.



Fix: Use std::array

and initialize in every constructor.

+1


source


As an alternative to using std::array

as the other answers show, you can use the described approach in this answer : mark the array as static in the class declaration (which is usually in the header file) and initialize it in the source file. For example:

test.h:

class TestClass
{
    static int a[3];
};

      

test.cpp:

int TestClass::a[3] = { 1, 2, 3 };

      

Eventually, this should become unnecessary as MSVC is catching up with C ++ 11.

0


source







All Articles