gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 19:52:18 25 4
gpt4 key购买 nike

为什么在 VS 2013 中编译

int main()
{

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

return 0;

}

但这给出了错误

class TestClass
{

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

};

我该如何解决?

最佳答案

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++ 上试过了,它也可以工作)。

关于c++ - 无法为数组指定显式初始值设定项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27882915/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com