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?
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:
test.cpp:
Eventually, this should become unecessary as MSVC catches up to C++11.
From Bjarne's C++11 FAQ page:
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):
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).