无法为数组指定显式初始值设定项

Can't specify explicit initializer for arrays

为什么要在 VS 2013 中编译

int main()
{

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

    return 0;

}

但这给出了错误

class TestClass
{

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

};

我该如何解决?

原因:尚未在该版本的 Visual C++ 中实现。

修复:使用 std::array 并在每个构造函数中初始化。

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).

问题是,VS2013 没有实现 C++11 的所有功能,而这是其中之一。所以我建议你使用 std::array (注意额外的大括号):

#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

如果您有兴趣,可以单击 on this link 以查看在使用已实现此功能的编译器(在本例中为 g++,我已经在 clang++ 上尝试过它)时,您所做的确实可以编译也有效)。

除了使用 std::array 作为其他答案的建议,您可以使用描述的方法 in this answer:在 class 声明中将数组标记为静态(通常是在头文件中),并在源文件中对其进行初始化。像这样:

test.h:

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

test.cpp:

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

最终,随着 MSVC 赶上 C++11,这应该变得不必要了。