在 C++ 中,我有一个包含匿名位域结构的类。我想将其初始化为零,而不必手动写出所有字段。
我可以想象将初始化放在三个地方:
- 在位域中创建构造函数
- 在包含类的构造函数的初始化列表中清零
- 在包含类的构造函数主体中清零
这个位域有很多字段,我不想一一列举。
例如看下面的代码:
class Big {
public:
Big();
// Bitfield struct
struct bflag_struct {
unsigned int field1 : 1;
unsigned int field2 : 2;
unsigned int field3 : 1;
// ...
unsigned int field20 : 1;
// bflag_struct(); <--- Here?
} bflag;
unsigned int integer_member;
Big *pointer_member;
}
Big::Big()
: bflag(), // <--- Can I zero bflag here?
integer_member(0),
pointer_member(NULL)
{
// Or here?
}
其中之一更可取吗?还是我还缺少其他东西?
编辑:根据下面接受的答案(由 Ferruccio 提供),我选择了这个解决方案:
class Big {
// ...
struct bflag_struct {
unsigned int field 1 : 1;
// ...
bflag_struct() { memset(this, 0, sizeof *this); };
}
// ...
}