考虑以下 :
#include <iostream>
#include <string>
using namespace std;
class A {
public:
A(const char* sName) //conversion constructor
: _sName(sName) {cout<<"(1)"<<endl;} ;
A(const A& s) {cout<<"(2)"<<endl;} //copy constructor
virtual ~A() {cout<<"(3)"<<endl;} //destructor
void f1() {cout<<"(4)"<<endl; f2();} //Notice two commands!
virtual void f2() =0;
private:
string _sName;
};
class B1: virtual public A {
public:
B1(const char* sAName, const char* sSName)
: _sName1(sAName), A(sSName) {cout<<"(5)"<<endl;}
B1(const B1& b1) : A(b1) {cout<<"(6)"<<endl;}
~B1() {cout<<"(7)"<<endl;}
virtual void f1() {cout<<"(8)"<<endl;}
virtual void f2() {cout<<"(9)"<<endl; f3();}
virtual void f3() {cout<<"(10)"<<endl;}
private:
string _sName1;
};
class B2: virtual public A {
public:
B2(const char* sAName, const char* sSName)
: _sName2(sAName), A(sSName) {cout<<"(11)"<<endl;}
B2(const B2& b2) : A(b2) {cout<<"(12)"<<endl;}
~B2() {cout<<"(13)"<<endl;}
virtual void f3() {f1(); cout<<"(14)"<<endl;}
private:
string _sName2;
};
class C: public B1, public B2 {
public:
C () : A(" this is A ") , B1(" this is " , " B1 ") , B2 (" this is " , " B2 ") {}
C (const C& c) : A(c) , B1(c) , B2(c) {}
~C() {cout<<"(15)"<<endl;}
virtual void f1() {A::f1(); cout<<"(16)"<<endl;}
void f3 () {cout<<"(17)"<<endl;}
};
int main() {
/* some code */
return 0;
}
如您所见,我在
class C
中添加了C的Ctor(构造函数)的实现。对我来说不清楚的是,如果B1在其Ctor中替我完成了工作,为什么还需要从C到A的上行链路?意思是,如果我将C的Ctor写成:
C () : A(" this is A ") , B1(" this is " , " B1 ") , B2 (" this is " , " B2 ") {}
我为什么不能写:
C () : B1(" this is " , " B1 ") , B2 (" this is " , " B2 ") {}
谢谢 ,
罗嫩
最佳答案
虚拟基础的构造函数在非虚拟anstors ctor之前被称为。在您的示例中,B1 ctor无法调用C的虚拟基构造函数,因为B1 ctor本身将在以后被调用。
关于c++ - 虚拟继承(钻石)-为什么我需要从派生程度最高的类转换为基本类,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/7267562/