考虑以下 :
#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 ") {}
谢谢,罗南