多个(菱形)继承编译没有“虚拟”,但不带 [英] Multiple (diamond) inheritance compiles without "virtual", but doesn't with
问题描述
给定以下代码(无虚拟继承):
Given the following code (without virtual inheritance) :
class A
{
public:
virtual void f() = 0;
};
class B : public A
{
public:
virtual void f() {}
};
class C : public A
{
public:
virtual void f() {}
};
class D : public B, public C
{
/* some code */
};
int main()
{
D d;
return 0;
}
代码编译。
另一方面,这里:
class A
{
public:
virtual void f() = 0;
};
class B : virtual public A
{
virtual void f() {}
};
class C : virtual public A
{
virtual void f() {}
};
class D : public B, public C
{
/* some code */
};
int main()
{
D d;
return 0;
}
编译器显示编译错误:
no unique final overrider for 'virtual void A::f()' in 'D' .
为什么在第二个代码中有所不同?
Why is it different in the second code ?
推荐答案
您的第一个场景层次结构对应于:
Your first scenario hierarchy corresponds to:
F() F()
A A
| |
F() B C F()
\ /
D
其中D不是抽象的,因为在类型D的对象中有两个A子对象:一个由B通过B的格子而具体化,另一个通过C的格子具体化。
Where D is not abstract, because there are two A subobjects in an object of type D: One that is made concrete by B through the lattice of B, and another that is made concrete through the lattice of C.
除非你试图在D的对象上调用函数F(),否则不会有任何歧义。
Unless you try to invoke the function F() on object of D there will not be any ambiguity.
对应于:
F()
A
/ \
F() B C F()
\ /
D
在这种情况下,对象D具有单个Base类A子对象,并且它必须重写并提供该子对象中纯虚函数的实现。
In this scenario, the object D has a single Base class A sub object, and it must override and provide implementation of the pure virtual function in that subobject.
Herb Sutter在Guru Of The Week(GOTW)中的文章是多重继承的好读法:
Herb Sutter's articles in Guru Of The Week(GOTW) are a nice read for Multiple Inheritance:
- Multiple Inheritance Part I
- Multiple Inheritance Part II
- Multiple Inheritance Part III
这篇关于多个(菱形)继承编译没有“虚拟”,但不带的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!