结构的数组成员的默认值

Default values for arrays members of struct

本文关键字:默认值 组成员 数组 结构      更新时间:2023-10-16

可能重复:
初始化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);