不能指定数组初始化明确 [英] Can't specify explicit initializer for arrays

查看:114
本文介绍了不能指定数组初始化明确的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么这个编译VS 2013

Why does this compile in VS 2013

int main()
{

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

    return 0;

}

但是这给了错误

class TestClass
{

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

};

如何解决呢?

推荐答案

从比亚的C ++ 11 FAQ页面

在C ++ 98,整型只有静态常量成员可以在类进行初始化,初始化必须有一个恒定的前pression。 [...]用于C ++ 11的基本思想是,以允许它被声明为初始化一个非静态数据成员(在它的类)。

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 ::阵列(注意额外的大括号中):

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;
}

上集合初始化CP preference链接

如果您有兴趣,可以点击这个链接看到你没有使用已经实现了这个功能的编译器时不编译(在这种情况下G ++,我已经试过了上铿锵++和它的作品太)。

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

这篇关于不能指定数组初始化明确的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆