How do you initialize the values of the following struct in a constructor to defined values?
Both options shown in my code example seem to be a bit ugly....
struct T_AnlagenInfo01
{
// Option A
T_AnlagenInfo01() : fReserve80_0(0), fReserve80_1(0),.... {};
// Option B
T_AnlagenInfo01()
{
memset(this, 0, sizeof(T_AnlagenInfo01));
}
unsigned long fReserve80_0 : 1;
unsigned long fReserve80_1 : 1;
unsigned long fReserve80_2 : 1;
unsigned long fReserve80_3 : 1;
unsigned long fReserve80_4 : 1;
unsigned long fReserve80_5 : 1;
unsigned long fReserve80_6 : 1;
unsigned long fReserve80_7 : 1;
unsigned long fReserve81_0 : 1; // 81
unsigned long fReserve81_1 : 1;
unsigned long fReserve81_2 : 1;
unsigned long fReserve81_3 : 1;
unsigned long fReserve81_4 : 1;
unsigned long fReserve81_5 : 1;
unsigned long fReserve81_6 : 1;
unsigned long fReserve81_7 : 1;
};
A bit field is a data structure that consists of one or more adjacent bits which have been allocated for specific purposes, so that any single bit or group of bits within the structure can be set or inspected.
Pointers and non-const references to bit-fields are not possible. When initializing a const reference from a bit-field, a temporary is created (its type is the type of the bit-field), copy initialized with the value of the bit-field, and the reference is bound to that temporary.
Both C and C++ allow integer members to be stored into memory spaces smaller than the compiler would ordinarily allow. These space-saving structure members are called bit fields, and their width in bits can be explicitly declared.
One obvious solution would be to put all of the bits in a separate structure, which is a member of your structure, and copy initialize that from a static member, e.g.:
struct T_AnlagenInfo01
{
struct Bits
{
unsigned long fReserve80_0 : 1;
unsigned long fReserve80_1 : 1;
// ...
};
Bits myBits;
static Bits initialBits;
T_AnlagenInfo01 : myBits(initialBits) {}
};
T_AnlagenInfo01::Bits T_AnlagenInfo01::initialBits = {};
This would even allow for certain bits to have a value different from 0.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With