问题描述
为什么是这样,虚构的构造函数基类是从大多数派生类调用的...在继承层次结构中,首先创建对象到虚拟基类...这是什么逻辑?
why is it so that the constructors of virtual base classes are called from most derived class...and in the inheritance hierarchy first the objects to virtual base classes are created...whats the logic behind this?
I理解,使用虚拟继承在钻石结构中使用虚拟继承只创建最基础类的一个副本,但是虚拟在线性继承。
I understand that using virtual inheritance as in diamond structure using virtual inheritance only one copy of the most base class is created but what exactly is virtual doing in a linear inheritance.
class A{};
class B : virtual public A {};
class C : virtual public B {};
我们在使用这种继承时实际上试图实现什么?
What actually we try to achieve on using this kind of inheritance?
还有什么是虚拟继承的对象布局?
Also what is the object layout in case of virtual inheritance ?
有人可以解释C ++中这种行为背后的逻辑吗?
Can someone explain the logic behind this kind of behaviour in C++?
推荐答案
虚拟继承应该是默认值。如果我写
,例如:
Virtual inheritance should arguably be the default. If I writesomething like:
class Base
{
public:
virtual ~Base() {}
virtual void f() = 0;
virtual int g() const = 0;
// ...
};
,很明显这个类是要继承的。如果我以后
写:
, it is clear that this class is meant to be inherited from. If I laterwrite:
class Middle : public virtual Base
{
public:
virtual void f();
};
,类仍然显然是一个基类,它只有
部分接口。在这种情况下,继承
应该是虚拟的,因为我不知道(或不想强加只是
一个解决方案)是否实现 g()
将在另一个
派生类中,或在一个姐妹类(mixin-technology)中。因此,
, the class is still clearly meant to be a base class—it has onlyimplemented part of the interface. In this case, the inheritanceshould be virtual, since I don't know (or don't want to impose justone solution) whether the implementation of g()
will be in a furtherderived class, or in a sister class (mixin-technology). Thus,
class Derived1 : public Middle
{
public:
virtual int g() const;
};
没有钻石,但作者 Middle
不知道这将是
的情况,并且不想禁止:
No diamand, but the author of Middle
didn't know that this would bethe case, and didn't want to forbid:
class M2 : public virtual Base
{
public:
virtual int g() const;
};
class Derived2 : public Middle, public M2
{
};
给定这样的层次结构,应该调用 Base
的构造函数。
只有合理的候选人是 Derived2
。
And given such a hierarchy, who should call Base
's constructor. Theonly reasonable candidate is Derived2
.
这篇关于为什么虚拟基类构造函数先调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!