多重(钻石)继承在没有“虚拟”的情况下进行编译,但不使用“虚拟”
给出以下代码(没有虚拟继承):
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' .
为什么第二个代码不同?
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;
}
the code compile.
On the other hand , here :
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;
}
The compiler presents a compilation error:
no unique final overrider for 'virtual void A::f()' in 'D' .
Why is it different in the second code ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的第一个场景层次结构对应于:
其中 D 不是抽象的,因为 D 类型的对象中有两个 A 子对象:一个由 B 通过 B 的晶格具体化,另一个通过 C 的晶格具体化除非
您尝试在 D 的对象上调用函数 F() ,否则不会有任何歧义。
您的第二个场景层次结构对应于:
在此场景中,对象 D 有一个基类 A 子对象,并且它必须重写并提供该子对象中纯虚函数的实现。
Herb Sutter 在 Guru Of The Week(GOTW) 中的文章对于多重继承来说是一本很好的读物:
Your first scenario hierarchy corresponds to:
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.
Unless you try to invoke the function F() on object of D there will not be any ambiguity.
Your second scenario hierarchy corresponds to:
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's articles in Guru Of The Week(GOTW) are a nice read for Multiple Inheritance:
通过虚拟继承,
D
对象具有单个基类A
子对象。这个单个子对象不能有虚拟函数的两个不同实现。相反,如果没有虚拟继承,D
对象有两个不同的基类A
子对象,每个子对象都有自己的函数实现(这是可以的,除非您尝试在D
对象上调用它,此时您需要指出您想要哪个)。干杯&嗯。
With the virtual inheritance a
D
object has a single base-classA
sub-object. This single sub-object can’t have two different implementations of a virtual function. In contrast, without virtual inheritance aD
object has two distinct base-classA
sub-objects, each with its own implementation of the function (which is OK until you try to call it on aD
object, at which point you need to indicate which one you want).Cheers & hth.