在联合中使用继承 [英] Using inheritance within a union
问题描述
我想知道是否有人知道是否可以以某种方式在联合中使用继承.
在下面的示例中,TestFails
联合将不包含 Base
结构中的 a
变量,而 TestWorks代码> 确实有效.
struct Base { int a;};联合测试失败{结构:公共基础{};国际b;};联合测试工厂{结构{ int a;};国际b;};int main(){TestWorks 有效;作品.a = 0;TestFails 失败;失败.a = 0;返回0;}
您可以在这里测试代码:http://ideone.com/dUzpOR
首先 - 您认为 TestWorks
有效的假设是错误的.这不是标准的 C++ - 只是它的扩展 - 它被称为 无名匿名struct - 当您使用迂腐选项进行编译时,您会得到:
prog.cc:5:27: 错误:ISO C++ 禁止匿名结构 [-Wpedantic]
结构:公共基础{};
<代码> ^
<块引用>
prog.cc:11:22: 错误:ISO C++ 禁止匿名结构 [-Wpedantic]
结构{ int a;};
要解决您的问题 - 只需命名这些匿名结构:
union TestFails{结构体:公共基础 {} s;//^国际b;};联合测试工厂{结构{ int a;} s;//^国际b;};
I was was wondering if anyone knows if it's possible to use inheritance within a union somehow.
In the example below, the TestFails
union will not contain the a
variable within the Base
struct, while TestWorks
does work.
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;
}
You can test the code here: http://ideone.com/dUzpOR
First of all - your assumption that TestWorks
works is wrong.
This is not standard C++ - only extension to it - it is called unnamed anonymous struct - and when you compile with pedantic options you get:
prog.cc:5:27: error: ISO C++ prohibits anonymous structs [-Wpedantic]
struct : public Base {};
^
prog.cc:11:22: error: ISO C++ prohibits anonymous structs [-Wpedantic]
struct { int a; };
To solve your issue - just name these anonymous structs:
union TestFails
{
struct : public Base {} s;
// ^
int b;
};
union TestWorks
{
struct { int a; } s;
// ^
int b;
};
这篇关于在联合中使用继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!