默认用许多布尔值初始化 class?

Default initialize a class with many boolean values?

注意:我不能使用c++11。

我有一个包含许多布尔值和一个字符串的 class。预计将在堆栈上使用。现在我用这个:

class Lorem: public Ipsulum {
public:
Lorem() :
    has_foo(0),
    is_bar(0),
    is_on(0),
    is_a_pony(0),
    has_car(0),
    foorbar()         // do I need this line if "foobar" is std::string?
{ }

private:
    bool has_foo;
    bool is_bar;
    bool is_off;
    bool is_a_pony;
    bool has_car;
    std::string foobar;  
}

问题 1:有没有办法让这个更简单?

问题 2: 我必须在列表中包含 "foorbar" 初始值设定项吗?

class Lorem: public Ipsulum {
public:
Lorem() :
    has_foo(0),
    is_bar(0),
    is_on(0),
    is_a_pony(0),
    has_car(0),
    foorbar("")         // do I need this line if "foobar" is std::string?
{ }

一定有用

不,没有更简单的方法,顺便说一下,当你初始化布尔变量时,使用 false 而不是 0 可能更清楚。

foobar不需要初始化,如果不初始化,会用默认构造函数构造。

Is there a way to do this simpler?

我猜你的意思是,有没有办法避免单独初始化每个 bool?您可以将它们放在一个结构中,然后对其进行值初始化:

Lorem() : flags() {}

private:
struct Flags {
    bool has_foo;
    bool is_bar;
    bool is_off;
    bool is_a_pony;
    bool has_car;
} flags;

或者将它们包装在强制值初始化的东西中

template <typename T> struct value_init {
    value_init() : value() {}
    T value;
};

value_init<bool> has_foo;

或者可能使用 std::bitset 或类似的。

Do I have to include the "foorbar" initializer in the list?

没有。那是一个带有默认构造函数的 class 类型;无论您是显式对其进行值初始化还是将其保留为默认初始化,都将使用该构造函数。