我正在尝试全局初始化union,如下例所示:
#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;
}
Run Code Online (Sandbox Code Playgroud)
但是,如果你运行代码,你会注意到temp.i或temp.t [...]实际上都没有提供正确的项目我初始化了联合.我想如果我可以手动初始化整数成员,这将被避免,但不幸的是我不能.我也无法改变结构中元素的排序(交换int和char命令正确地初始化所有内容) - 它们实际上是由外部库提供的.我的问题是:如何全局设置结构的整数成员,而不是char [4]成员(或者,在这种情况下,只是char []的第一个元素)?
编辑:此外,这个问题是否有严格的c ++解决方案?即命名结构初始化不起作用的一个(因为它在语言中不存在)?
你想要这样做:
a temp = {i: w};
Run Code Online (Sandbox Code Playgroud)
这应该适用于gcc和g++.
在C99中,您可以使用命名初始化,如下所示:
a x = { .i = 10 };
Run Code Online (Sandbox Code Playgroud)
有一些建议使用非标准的gcc扩展,但如果编码C我会避免它:
a x = { i : 10 };
Run Code Online (Sandbox Code Playgroud)
您可以使用函数初始化:
inline a initialize( int value ) { // probably choose a better name
a tmp;
tmp.i = value;
return a;
}
Run Code Online (Sandbox Code Playgroud)
然后使用:
a x = initialize( 10 );
Run Code Online (Sandbox Code Playgroud)
编译器将优化副本.
如果您正在使用C++,则可以为union类型提供构造函数:
/*typedef*/ union u { // typedef is not required in general in C++
char bytes[sizeof(int)];
int i;
u( int i = 0 ) : i(i) {}
} /*u*/;
u x( 5 );
Run Code Online (Sandbox Code Playgroud)