简体   繁体   中英

How to initialize a struct with union?

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);
        }
    }
}

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM