无效的工会会员 [英] Invalid union member

查看:95
本文介绍了无效的工会会员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Visual Studio中是否有一种处理非平凡联合的方法.使用g++ -std=c++11,以下代码可以正常运行,但VS抱怨:

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:

无效的工会成员-类"Foo"具有不允许的成员函数

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

代码如下:

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

Visual Studio中是否有一种方法可以支持这种联合(例如,编译选项)?还是应该更改我的代码,如果要更改呢?

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?

推荐答案

我同意@Shafik Yaghmour,但是有一个简单的解决方法.
只需将您的foo成员放入unnamed struct中,就像这样:

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

这篇关于无效的工会会员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆