ALO*_*low 5 c++ arrays constructor struct initialization
可能重复:
对C++类中的数组进行初始化和可修改的左值问题
正如在这个问题中看到的那样,可以给一个结构提供一个ctor,使其成员获得默认值.您将如何继续为结构内的数组的每个元素提供默认值.
struct foo
{
int array[ 10 ];
int simpleInt;
foo() : simpleInt(0) {}; // only initialize the int...
}
Run Code Online (Sandbox Code Playgroud)
有没有办法在一行中使用类似于初始化int的方法?
新的C++标准有一种方法可以做到这一点:
struct foo
{
int array[ 10 ];
int simpleInt;
foo() : array{1,2,3,4,5,6,7,8,9,10}, simpleInt(0) {};
};
Run Code Online (Sandbox Code Playgroud)
如果你的编译器还不支持这种语法,你总是可以分配给数组的每个元素:
struct foo
{
int array[ 10 ];
int simpleInt;
foo() : simpleInt(0)
{
for(int i=0; i<10; ++i)
array[i] = i;
}
};
Run Code Online (Sandbox Code Playgroud)
编辑:在2011前C单行溶液++需要不同的容器类型,例如C++矢量(其无论如何优选)或升压阵列,其可以是boost.assign "编
#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) {};
};
Run Code Online (Sandbox Code Playgroud)