C++ 和 C 中的联合初始化
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11555702/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Union initialization in C++ and C
提问by Alex
I have built a working C library, that uses constants, in header files defined as
我在定义为的头文件中构建了一个使用常量的工作 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 } };
I know that the .raw
initializer is C only syntax.
我知道.raw
初始化程序是仅 C 语法。
How do I define constants with unions in them in a way such that I can use them in C and C++.
我如何定义带有联合的常量,以便我可以在 C 和 C++ 中使用它们。
采纳答案by hae
I had the same problem. For C89 the following is true:
我有同样的问题。对于 C89,以下是正确的:
With C89-style initializers, structure members must be initialized in the order declared, and only the first member of a union can be initialized
使用 C89 样式的初始化器,结构成员必须按照声明的顺序进行初始化,并且只能初始化联合的第一个成员
I found this explanation at: Initialization of structures and unions
我在以下位置找到了这个解释: 结构和联合的初始化
回答by Kerrek SB
I believe that C++11 allows you to write your own constructor like so:
我相信 C++11 允许您像这样编写自己的构造函数:
union Foo
{
X x;
uint8_t raw[sizeof(X)];
Foo() : raw{} { }
};
This default-initializes a union of type Foo
with active member raw
, which has all elements zero-initialized. (Before C++11, there was no way to initialize arrays which are not complete objects.)
这默认初始化了一个类型Foo
为 active member的 union raw
,它的所有元素都被初始化为零。(在 C++11 之前,无法初始化不是完整对象的数组。)
回答by Alex
I decided to choose the following path.
我决定选择以下路径。
- Do not use
.member
initialization. - do nost use
static const struct Foobar
initialization of members
- 不要使用
.member
初始化。 - 不要使用
static const struct Foobar
成员初始化
Instead declare the global variable:
而是声明全局变量:
extern "C" {
extern const struct Foobar foobar;
}
and initialize it in a global section:
并在全局部分初始化它:
struct Foobar foobar = { 0, 0, 0, 0 };
and instead of bugging the C++ compiler with modern ANSI C99 syntax I let the linker do the work be demangling C symbols.
而不是用现代 ANSI C99 语法来干扰 C++ 编译器,我让链接器完成对 C 符号进行分解的工作。