Reputation: 13
How can I properly initialize a struct which contains a union? Currently I get an error // 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);
}
}
}
Upvotes: 1
Views: 934
Reputation: 366
What is the reason You want to use union? Unions are great for saving memory. In c++ rarely there is a need to use them. I know that is not the answer for your question but think if You have to use them in this project.
Upvotes: 0
Reputation: 409166
When initializing a union, only the first member will be initialized. Rearrange the union so that float real
becomes the first member of the union.
Of course, that means you can't use the other members in direct initialization.
The other solution is to add a constructor to the union, like one for the real
member, one for the string
member and one for the pointer
member.
Upvotes: 4