如何正确初始化包含 union 的结构?目前我收到错误 //error C2440: 'initializing': cannot convert from 'float' to 'const char *'
#include <stdio.h>
using namespace std;
typedef enum {STRING, REAL, POINTER } Type;
const struct Entry {
union {
const char *string;
float real;
void *pointer;
};
Type type;
LPCSTR Key;
LPCSTR Name;
}f;
const Entry Entries[] = {
{{0.5f}, REAL, "Key", "Name" } // error C2440: 'initializing': cannot convert from 'float' to 'const char *'
};
int main(int argc, char **argv)
{
for (int i = 0; i < size(Entries); i++)
{
switch Entries[i].type
{
case STRING:
printf("Type string; Value: %s\n", Entries[i].string);
case REAL:
printf("Type string; Value: %d\n", Entries[i].real);
}
}
}
最佳答案
初始化 union 时,只有第一个 成员会被初始化。重新排列 union ,使 float real
成为 union 的第一个成员。
当然,这意味着您不能在直接初始化中使用其他成员。
另一种解决方案是向 union 体添加一个构造函数,比如一个用于real
成员,一个用于string
成员,一个用于pointer
成员。
关于c++ - 如何用 union 初始化结构?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54231202/