对于结构数组成员默认值 [英] Default values for arrays members of struct

查看:116
本文介绍了对于结构数组成员默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:结果
  <一href=\"http://stackoverflow.com/questions/6647038/intitialzing-an-array-in-a-c-class-and-modifiable-lvalue-problem\">Intitialzing在C ++类和修改的左值问题的一个阵列

作为<一看到href=\"http://stackoverflow.com/questions/1069621/are-members-of-a-c-struct-initialized-to-0-by-default\">this问题,有可能给一个构造函数为结构,使其成员得到默认值。你将如何继续给一个默认值一个结构里的数组中的每个元素。

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...
}

有没有一些方法,使这类似于你会怎么做初始化一个int一行?

Is there some way to make this in one line similar to how you would do to initialize an 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) {};
};

测试: https://ideone.com/enBUu

如果你的编译器不支持此语法的是,你总是可以分配到阵列中的每个元素:

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;
   }
};

编辑:在pre-2011下1班轮解决方案++需要不同的容器类型,如C ++向量(这是无论如何pferred $ P $),或提振阵列,它可以是的 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) {};
};

这篇关于对于结构数组成员默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆