简体   繁体   English

如何在初始化列表中初始化普通数组成员变量?

[英]How can I initialize normal array member variable in initializer list?

I would like to do the following: 我要执行以下操作:

class MyClass {
    public:
        MyClass() : arr({1,2,3,4,5,6,7,8}) {}

    private:
        uint32_t arr[8];
};

but it doesn't work (compiler: expected primary expression before '}' token.). 但它不起作用(编译器:“}”标记之前的预期主表达式。)。 I've looked at other SO questions and people were passing around things like std::initializer_list , and trying interesting things like placing the array initializer in double braces like so: 我看过其他SO问题,人们绕过了诸如std::initializer_list类的东西,并尝试了一些有趣的事情,例如将数组初始化器放在双括号中,例如:

MyClass() : arr( {{1,2,3,4,5,6,7,8}} ) {}

but I'm unfamiliar with the purpose of std::initializer_list and also I'm not quite sure why there's double braces in the above code (though it doesn't work anyway, so I'm not sure why it matters). 但是我不了解std::initializer_list的用途,并且我也不太确定为什么上面的代码中有两个大括号(尽管无论如何还是不起作用,所以我不确定为什么很重要)。

Is there a normal way to achieve initialization of my arr variable in a constructor initializer list? 有没有一种正常的方法可以在构造函数初始化器列表中实现对arr变量的初始化?

Your syntax is correct. 您的语法正确。 Alternatively, you can say arr{1,2,3,...} . 或者,您可以说arr{1,2,3,...}

Most likely is that your compiler just doesn't support this construction yet. 最有可能的是您的编译器尚不支持这种构造。 GCC 4.4.3 and 4.6.1 both do (with -std=c++0x ). GCC 4.4.3和4.6.1都可以使用( -std=c++0x )。

Works perfectly on GCC 4.5.2 with -std=gnu++0x. 在带有-std = gnu ++ 0x的GCC 4.5.2上完美工作。 I get a warning and a freeze with -std=c++98. 我收到警告,并使用-std = c ++ 98冻结。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用 initializer_list 初始化成员数组? - How do I initialize a member array with an initializer_list? 如何在成员初始值设定项列表中初始化数组 - How to initialize an array in the member initializer list 在成员初始化器列表中,我可以创建对不在列表中的成员变量的引用吗? - In the member initializer list, can I create a reference to a member variable not in the list? 如何使用初始化列表初始化2D矢量成员? - How can I use an initializer list to initialize a 2D vector member? 如何使用成员初始化列表初始化数组? - How can i use member initialization list to initialize an array? 如何让我的数组 class 实例使用初始化列表来初始化数组 - How can I get my array class instance to use initializer list to initialize the array 如何在成员初始值设定项列表之外初始化类成员 - How to initialize class member outside the member initializer list 我想在组合/整体 class 的成员初始化程序列表中初始化一个“部分”数组 class - I want to initialize an array of "part" class in member initializer list of composed/whole class 如何在varargs构造函数的初始化列表中初始化向量? - How can I initialize a vector in the initializer list of a varargs constructor? 我可以使用 std::initializer_list 而不是大括号封闭的初始化程序来初始化数组吗? - Can I initialize an array using the std::initializer_list instead of brace-enclosed initializer?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM