新的 C++ 标准有一个方法可以做到这一点:
struct foo
{
int array[ 10 ];
int simpleInt;
foo() : array{1,2,3,4,5,6,7,8,9,10}, simpleInt(0) {};
};
test: https://ideone.com/enBUu https://ideone.com/enBUu
如果您的编译器尚不支持此语法,您始终可以分配给数组的每个元素:
struct foo
{
int array[ 10 ];
int simpleInt;
foo() : simpleInt(0)
{
for(int i=0; i<10; ++i)
array[i] = i;
}
};
编辑:2011 年之前的 C++ 中的单行解决方案需要不同的容器类型,例如 C++ 矢量(无论如何都是首选)或 boost 数组,它们可以是升压分配 http://www.boost.org/doc/libs/release/libs/assign/doc/index.html'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) {};
};