如何正确初始化包含联合的结构?目前,我收到一个错误// 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);
}
}
}
最佳答案
初始化联合时,仅第一个成员将被初始化。重新排列联合,以便float real
成为联合的第一个成员。
当然,这意味着您不能在直接初始化中使用其他成员。
另一种解决方案是将一个构造函数添加到联合中,例如一个用于real
成员,一个用于string
成员和一个用于pointer
成员。
关于c++ - 如何用 union 初始化结构?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/54231202/