工会初始化 [英] union initialisation
问题描述
我试图在全球范围内初始化工会如下面的例子:
I'm attempting to globally initialise a union as in the following example:
#include <cstdio>
typedef union {
char t[4];
int i;
} a;
enum {
w = 5000,
x,
y,
z
};
a temp = {w};
int main() {
printf("%d %d %d %d %d\n", temp.t[0],temp.t[1],temp.t[2],temp.t[3],temp.i);
return 0;
}
不过,如果您运行code,你会注意到,无论是temp.i或temp.t的[...]实际上给正确的项目我初始化工会有。我想这将是可以避免的,如果我可以手动初始化整数成员,但遗憾的是我不能。我也无法改变元素的顺序的结构(交换int和焦炭为了初始化一切正常)内 - 他们实际上是由外部库提供。
我的问题是:我怎么能设置结构的整数成员的全球的,而不是将char [4]成员(或者,在这种情况下,刚刚的char []的第一个元素)?
However, if you run the code, you'll note that neither of temp.i or temp.t[...] actually give the correct item i initialised the union with. I'd imagine this would be avoided if I could manually initialise the integer member, but unfortunately I can't. I also can't change the ordering of elements within the struct (swapping the int and char order initialises everything properly) - they're actually provided by an external library. My question is this: how can I set the integer member of the structure globally, rather than the char[4] member (or, in this case, just the first element of the char[])?
编辑:此外,有没有一个严格的-C ++解决这个问题?即,一个在这里命名结构初始化不起作用(因为它没有在语言存在)?
Also, is there a strictly-c++ solution to this problem? i.e. one where named struct initialisation doesn't work (because it doesn't exist in the language)?
推荐答案
您想做到这一点:
a temp = {i: w};
这应为 GCC
和 G ++
。
这篇关于工会初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!