如何虚拟继承解决“钻石” (多重继承)模糊? [英] How does virtual inheritance solve the "diamond" (multiple inheritance) ambiguity?
问题描述
class A { public: void eat(){ cout<<"A";} };
class B: virtual public A { public: void eat(){ cout<<"B";} };
class C: virtual public A { public: void eat(){ cout<<"C";} };
class D: public B,C { public: void eat(){ cout<<"D";} };
int main(){
A *a = new D();
a->eat();
}
我理解钻石问题,上面的代码没有这个问题。
I understand the diamond problem, and above piece of code does not have that problem.
虚拟继承如何解决这个问题?
How exactly does virtual inheritance solve the problem?
我理解:
当我说 A * a = new D();
时,编译器想知道类型 D
可以分配给
A
类型的指针,但它有两个路径,它可以跟随,但不能自行决定。
What I understand:
When I say A *a = new D();
, the compiler wants to know if an object of type D
can be assigned to a pointer of type A
, but it has two paths that it can follow, but cannot decide by itself.
因此,虚拟继承如何解决问题(帮助编译器做出决定)?
So, how does virtual inheritance resolve the issue (help compiler take the decision)?
推荐答案
您需要:(可通过虚拟继承实现)
You want: (Achievable with virtual inheritance)
D
/ \
B C
\ /
A
:(无虚拟继承会发生什么)
And not: (What happens without virtual inheritance)
D
/ \
B C
| |
A A
虚拟继承意味着只有一个基础实例 A
类不是2.
Virtual inheritance means that there will be only 1 instance of the base A
class not 2.
您的类型 D
指针(您可以在第一个图表中看到它们),一个用于 B
,一个用于 C
c $ c> A 。 D
的对象大小增加,因为它现在存储2个指针;但是现在只有一个 A
。
Your type D
would have 2 vtable pointers (you can see them in the first diagram), one for B
and one for C
who virtually inherit A
. D
's object size is increased because it stores 2 pointers now; however there is only one A
now.
因此 B :: A
和 C :: A
是相同的,因此不能有 D
的模糊调用。如果你不使用虚拟继承,你有上面的第二个图。然后,任何对A成员的调用都会变得模糊,您需要指定要采用的路径。
So B::A
and C::A
are the same and so there can be no ambiguous calls from D
. If you don't use virtual inheritance you have the second diagram above. And any call to a member of A then becomes ambiguous and you need to specify which path you want to take.
这篇关于如何虚拟继承解决“钻石” (多重继承)模糊?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!