struct的数组成员的默认值 [英] Default values for arrays members of struct
问题描述
可能重复:
在C ++类中初始化数组和可修改的左值问题
如这个问题,它可以给一个ctor一个结构,使其成员获得默认值。你将如何继续给结构中数组的每个元素赋予默认值。
As seen in this question, it's possible to give a ctor to a struct to make it members get default values. How would you proceed to give a default value to every element of an array inside a struct.
struct foo
{
int array[ 10 ];
int simpleInt;
foo() : simpleInt(0) {}; // only initialize the int...
}
推荐答案
Thew新的C ++标准有一个方法来做到这一点:
Thew new C++ standard has a way to do this:
struct foo
{
int array[ 10 ];
int simpleInt;
foo() : array{1,2,3,4,5,6,7,8,9,10}, simpleInt(0) {};
};
如果您的编译器不支持此语法,则可以始终分配给数组的每个元素:
If your compiler does not support this syntax yet, you can always assign to each element of the array:
struct foo
{
int array[ 10 ];
int simpleInt;
foo() : simpleInt(0)
{
for(int i=0; i<10; ++i)
array[i] = i;
}
};
编辑:在2011之前的C ++中的一线解决方案需要不同的容器类型,如C ++向量这是首选的)或boost数组,可以提高.assign 'ed
one-liner solutions in pre-2011 C++ require different container types, such as C++ vector (which is preferred anyway) or boost array, which can be boost.assign'ed
#include <boost/assign/list_of.hpp>
#include <boost/array.hpp>
struct foo
{
boost::array<int, 10> array;
int simpleInt;
foo() : array(boost::assign::list_of(1)(2)(3)(4)(5)(6)(7)(8)(9)(10)),
simpleInt(0) {};
};
这篇关于struct的数组成员的默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!