结构的数组成员的默认值
Default values for arrays members of struct
可能重复:
初始化C++类中的数组和可修改的左值问题
正如在这个问题中看到的,可以给结构一个ctor,使其成员获得默认值。如何继续为结构中数组的每个元素指定默认值。
struct foo
{
int array[ 10 ];
int simpleInt;
foo() : simpleInt(0) {}; // only initialize the int...
}
是否有某种方法可以在一行中实现这一点,类似于初始化int的方法?
新的C++标准有一种方法可以做到这一点:
struct foo
{
int array[ 10 ];
int simpleInt;
foo() : array{1,2,3,4,5,6,7,8,9,10}, simpleInt(0) {};
};
测试: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阵列,它们可以是boost。指定的
#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) {};
};
将数组更改为std::vector将允许您进行简单的初始化,并且您将获得使用vector的其他好处。
#include <vector>
struct foo
{
std::vector<int> array;
int simpleInt;
foo() : array(10, 0), simpleInt(0) {}; // initialize both
};
如果你只想默认初始化数组(将内置类型设置为0(,你可以这样做:
struct foo
{
int array[ 10 ];
int simpleInt;
foo() : array(), simpleInt(0) { }
};
#include <algorithm>
struct foo
{
int array[ 10 ];
int simpleInt;
foo() : simpleInt(0) { std::fill(array, array+10, 42); }
};
或者在生成器由您决定的情况下使用std::generate(begin, end, generator);
。
相关文章:
- 如何将数组部分初始化为某个默认值?
- 为什么在使用指针时不采用类成员的默认值,而不是直接实例化对象时?
- C++中未初始化成员布尔变量的默认值是多少?
- c++ 中堆上数组的默认值是多少?
- 为什么不能使用"( )"为类的非静态数据成员提供默认值?
- C++不同内存位置中的默认数组值
- 使用默认值初始化成员引用
- 使用默认值初始化 std::数组
- 模板类专业化具有成员变量和方法的默认值
- 初始化类成员 - 默认值还是成员初始化列表?
- 具有类成员默认值的 C++11 默认构造函数行为
- 为什么 const char 数组成员的初始化在构造函数初始值设定项中不兼容
- 用作函数参数时,将默认值设置为 C 数组
- 在C 中声明具有默认值的大型数组
- 通过drived类模板值通过基类构造器初始化基类数组成员变量
- 受保护成员 c++ 的默认值
- 如何使用常量成员值初始化数组成员
- 类中数组成员C++11的默认初始值设定项
- boost::绑定具有默认值的成员函数
- 结构的数组成员的默认值