【问题标题】:How can an array be initialized in a constructor? [duplicate]如何在构造函数中初始化数组? [复制]
【发布时间】:2012-02-15 12:49:17
【问题描述】:

可能重复:
initialize a const array in a class initializer in C++

如果我有一个类的成员变量是布尔数组,我如何将构造函数的初始化列表中的数组初始化为所有假值?还是会默认初始化为全false?

class example {
public:
  example()
    : // What goes here to initialize _test to 64 false values?
  {
  }

private:
  bool _test[64];
};

【问题讨论】:

  • 不,默认情况下它们没有初始化为空。你不能遍历所有元素吗?
  • 为什么不在构造函数中只用一个for循环来做呢?您还可以使用效率更高的 memset。
  • @guitarflow : 在 for 循环内(构造函数内)将元素赋值为 0 不是初始化

标签: c++ arrays constructor boolean initializer-list


【解决方案1】:
example() :_test()
    : // zero initialization
  {
  }

【讨论】:

  • 这行得通吗?我猜用 bools 这会用错误值预设数组?
  • @guitarflow :问题是“如何将构造函数的初始化列表中的数组初始化为所有 false 值?”
  • 当然,我只是没见过这种形式。如果是 bool,您还可以使用它来将其初始化为其他 int 值或 true 吗?
  • @guitarflow : 不,我们只能使用它为零(在非 POD 的情况下初始化值)初始化元素。
【解决方案2】:

类似:

class example {
public:
  example()
    : _test()
  {  
  }

private:
  bool _test[64];
};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-09-25
    • 2012-05-12
    • 1970-01-01
    • 2017-08-16
    • 1970-01-01
    • 1970-01-01
    • 2011-05-02
    • 1970-01-01
    相关资源
    最近更新 更多