问题描述
编译器如何实现虚拟继承?
在以下代码中:
code> class A {
public:
A(int){}
};
class B:public virtual A {
public:
B():A(1){}
};
class C:public B {
public:
C():A(3),B(){}
};编译器生成两个B :: ctor函数的实例,一个没有调用A(1)和一个与它?因此,当从派生类的构造函数调用B :: constructor时,使用第一个实例,否则使用第二个。解决方案依赖。 GCC(请参阅),例如,将发出两个构造函数,一个具有调用
A(1)
,另一个没有。B1 )
B2()// no A
构建B时,版本被调用:
B1():
A(1)
B $ b构建C时,将调用基本版本:
$ b bC():
A(3)
B2()
B $ b事实上,即使没有虚拟继承,也会抛出两个构造函数, / p>
How the compilers implement the virtual inheritance?
In the following code:
class A { public: A(int) {} }; class B : public virtual A { public: B() : A(1) {} }; class C : public B { public: C() : A(3), B() {} };
Does a compiler generate two instance of B::ctor function, one without A(1) call, and one with it? So when B::constructor is called from derived class's constructor the first instance is used, otherwise the second.
解决方案It's implementation-dependent. GCC (see this question), for example, will emit two constructors, one with a call to
A(1)
, another one without.B1() B2() // no A
When B is constructed, the "full" version is called:
B1(): A(1) B() body
When C is constructed, the base version is called instead:
C(): A(3) B2() B() body C() body
In fact, two constructors will be emitted even if there is no virtual inheritance, and they will be identical.
这篇关于如何在编译器中实现C ++虚拟继承?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!