Art*_*too 7 c++ inheritance unions
我想知道是否有人知道是否有可能以某种方式在联盟中使用继承.
在下面的示例中,TestFailsunion将不包含struct中的a变量Base,同时TestWorks确实有效.
struct Base { int a; };
union TestFails
{
struct : public Base {};
int b;
};
union TestWorks
{
struct { int a; };
int b;
};
int main()
{
TestWorks works;
works.a = 0;
TestFails fails;
fails.a = 0;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
您可以在此处测试代码:http://ideone.com/dUzpOR
不确定是否有帮助,但这有效:
struct Base { int a; };
struct Foo : Base { int b;};
union TestFailsNot {
Base base;
Foo foo;
int b;
};
int main() {
TestFailsNot failsNot;
failsNot.foo.a = 0;
failsNot.base.a = 3; // maybe not what you want to do, but it works
}
Run Code Online (Sandbox Code Playgroud)