Ale*_*lex 29 c c++ initialization unions c++03
我已经在定义为的头文件中构建了一个使用常量的工作C库
typedef struct Y {
union {
struct bit_field bits;
uint8_t raw[4];
} X;
} CardInfo;
static const CardInfo Y_CONSTANT = { .raw = {0, 0, 0, 0 } };
Run Code Online (Sandbox Code Playgroud)
我知道.raw初始化程序只是C语法.
如何在其中使用联合定义常量,以便我可以在C和C++中使用它们.
我相信 C++11 允许您像这样编写自己的构造函数:
union Foo
{
X x;
uint8_t raw[sizeof(X)];
Foo() : raw{} { }
};
Run Code Online (Sandbox Code Playgroud)
这默认初始化了一个类型Foo为 active member的 union raw,它的所有元素都被初始化为零。(在 C++11 之前,无法初始化不是完整对象的数组。)