考慮以下上溯造型到基類:虛擬繼承(鑽石) - 做我爲什麼需要從最派生類
#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到A的倒戈,如果B1在Ctor爲我做這項工作? 意義,如果我寫的C'S構造函數爲:
C() : A(" this is A ") , B1(" this is " , " B1 ") , B2 (" this is " , " B2 ") {}
我爲什麼不能寫:
C() : B1(" this is " , " B1 ") , B2 (" this is " , " B2 ") {}
感謝, 羅南
即使第二種格式可以工作,只要在抽象類A中存在缺省構造函數即可。缺少該缺省構造函數是第二種格式不能編譯的真正原因,請參閱我的答案。 –
@Als:我同意你的回答,但是沒有任何矛盾。虛擬基礎ctor被大多數派生類ctor調用。 Base Ctor可能是默認的或不是。在這種情況下,簡單地忽略中間ctor中的虛擬基礎調用 – user396672