无法为数组指定显式初始化程序 [英] Can't specify explicit initializer for arrays

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

问题描述

为什么在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 };

};

如何修复?

推荐答案

从Bjarne的C ++ 11常见问题页面


在C ++ 98中,只有整数类型的静态const成员可以在类中初始化,初始化器必须是常量表达。 [...] 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 :: array(注意额外的大括号):

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

如果您有兴趣,可以点击在这个链接,看看你做了什么做编译时使用的编译器已实现这个功能(在这种情况下g ++,我试过它clang ++和它也工作)。

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天全站免登陆