Why does this compile in VS 2013
int main()
{
int a[3] = { 1, 2, 3 };
return 0;
}
but this gives the error
class TestClass
{
int a[3] = { 1, 2, 3 };
};
How do I fix it?
Why does this compile in VS 2013
int main()
{
int a[3] = { 1, 2, 3 };
return 0;
}
but this gives the error
class TestClass
{
int a[3] = { 1, 2, 3 };
};
How do I fix it?
From Bjarne's C++11 FAQ page:
In C++98, only static const members of integral types can be initialized in-class, and the initializer has to be a constant expression. [...] The basic idea for C++11 is to allow a non-static data member to be initialized where it is declared (in its class).
The problem is, VS2013 doesn't implement all the features of C++11, and this is one of them. So what I suggest you use is std::array (take note of the extra set of 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 link on aggregate initialization
If you're interested you can click on this link to see that what you did does compile when using a compiler that has implemented this feature (in this case g++, I've tried it on clang++ and it works too).
Why: not yet implemented in that version of Visual C++.
Fix: use std::array
and initialize in each constructor.
In alternative to using std::array
as the other answers suggest, you can use the approach described in this answer: mark the array as static in the class declaration (which would usually be in the header file), and initialize it in the source file. Like so:
test.h:
class TestClass
{
static int a[3];
};
test.cpp:
int TestClass::a[3] = { 1, 2, 3 };
Eventually, this should become unecessary as MSVC catches up to C++11.