Invalid union member

北战南征 提交于 2019-12-07 02:24:11

问题


Is there a way in Visual Studio to handle non-trivial unions. The following code is running fine using g++ -std=c++11 but VS complains:

invalid union member -- class "Foo" has a disallowed member function

The code is as follows:

struct Foo {
    int value;
    Foo(int inV = 0) : value(inV) {}
};

union CustomUnion {
    CustomUnion(Foo inF) : foo(inF) {}
    CustomUnion(int inB) : bar(inB) {}
    int bar;
    Foo foo;
};

int main() {
    CustomUnion u(3);
    return 0;
}

Is there a way in Visual Studio to support this kind of unions (compilation option for instance)? Or should I change my code, and if so by what?


回答1:


I agree with @Shafik Yaghmour but there is an easy workaround.
Just put your foo member into an unnamed struct like so:

union CustomUnion {
    struct{
        Foo foo;
    };
    int bar;
};



回答2:


Visual Studio does not support unrestricted unions which is a C++11 feature that allows unions to contain non-POD types, in your case Foo has a non-trivial constructor since you have defined one.

I don't see any reference that says when Visual Studio will support this so it does not seem like you will get this to work as is in Visual Studio. Although there seems to be many who do want this feature supported.

The only way I can see to get to work would be to remove your user defined constructor from Foo. That would mean manually initializing foo in the CustomUinon constructor.

A good reference article would be: C++11 Standard Explained: 1. Unrestricted Union .




回答3:


As described in msdn, union just accesses members: 1) class type without any constructors or destructors, 2) static member, 3) class type without user defined assignment operation(override =).




回答4:


I've received this same error, but my situation may be different. Turns out that the union is looking for a default constructor.

So within my class I had to do this:

struct Foo
{
    union
    {
        Bar bar; // intellisense will still show error, but you can ignore it.
    };
};

And within you Bar class, instead of creating a traditional default constructor Bar(); and defining it, change it to Bar() = default; and erase your default constructor definition in your .cpp file. You will still see the error for Bar bar, because intellisense doesn't know exactly what's going on. Your application will still compile regardless if this helps.



来源:https://stackoverflow.com/questions/21968635/invalid-union-member

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!