Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/159.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/72.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 工会初始化_C++_C_Unions - Fatal编程技术网

C++ 工会初始化

C++ 工会初始化,c++,c,unions,C++,C,Unions,我正在尝试全局初始化工会,如下例所示: #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); r

我正在尝试全局初始化工会,如下例所示:

#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;
}
#包括
typedef联合{
chart[4];
int i;
}a;
枚举{
w=5000,
x,,
Y
Z
};
a temp={w};
int main(){
printf(“%d%d%d%d%d\n”、温度t[0]、温度t[1]、温度t[2]、温度t[3]、温度i);
返回0;
}
但是,如果您运行代码,您会注意到temp.i或temp.t[…]实际上都没有给出我初始化联合所用的正确项。我想,如果我可以手动初始化integer成员,这将是可以避免的,但不幸的是,我不能。我也不能改变结构中元素的顺序(交换int和char顺序可以正确初始化所有元素)——它们实际上是由外部库提供的。 我的问题是:如何全局设置结构的整数成员,而不是char[4]成员(或者,在本例中,仅设置char[]的第一个元素)


编辑:还有,这个问题有没有严格的c++解决方案?i、 e.命名结构初始化不起作用(因为它在语言中不存在)?

在C99中,您可以这样做:

a temp = { .i=w };

您可以按如下方式初始化integer成员:

a temp = {
  .i = w
};

您可能希望执行以下操作:

a temp = {i: w};

这应该适用于
gcc
g++

在C99中,您可以使用命名初始化,如下所示:

a x = { .i = 10 };
有一些关于使用非标准gcc扩展的建议,但是如果编码C,我会避免使用它:

a x = { i : 10 };
您可以使用函数初始化:

inline a initialize( int value ) { // probably choose a better name
   a tmp;
   tmp.i = value;
   return a;
}
然后使用:

a x = initialize( 10 );
编译器将优化副本

如果你正在做C++,你可以为你的联合类型提供一个构造器:

/*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 );

啊,美丽;这就是我要找的。请注意,这是一个非标准的语言扩展,如果转移到其他编译器,这将失败。是的,这就是我提到gcc/g++的原因。似乎没有一个有效的C++方法来初始化工会成员。问题是我不能修改工会本身,否则我只需要重新排列这些元素并用它来完成。不过,我确实喜欢内联方法。