通常,一个类的构造函数只初始化自己的变量和基类。然而,虚继承的基类是一个例外。它们由它们的派生性最强的恶类初始化。
有个继承关系如下:
Animal
/ \
Horse Bird
\ /
Pegasus
#include<iostream> using namespace std; class Animal{ public: Animal(){cout<<"Animal constructor!"<<endl;} virtual ~Animal(){cout<<"Animal deconstructor!"<<endl;} };
class Horse : virtual public Animal{ public: Horse(){cout<<"Horse constructor!"<<endl;} virtual ~Horse(){cout<<"Horse deconstructor!"<<endl;} virtual void Run(){ cout<<"Horse run!"<<endl;} };
class Bird : virtual public Animal{ public: Bird(){cout<<"Bird constructor!"<<endl;} virtual ~Bird(){cout<<"Bird deconstructor!"<<endl;} virtual void Fly(){ cout<<"Bird fly!"<<endl;} };
class Pegasus : public Horse, public Bird{ public: Pegasus(){cout<<"Pegasus constructor!"<<endl;} virtual ~Pegasus(){cout<<"Pegasus deconstructor!"<<endl;} void Speak(){ cout<<"Pegasus speak!"<<endl;} void Fly(){ cout<<"Pegasus fly!"<<endl;} };
int main(){ Pegasus* p; p=new Pegasus; //Animal constructor! //Horse constructor! //Bird constructor! //Pegasus constructor!
p->Speak(); //Pegasus speak! p->Fly(); //Pegasus fly! p->Run(); //Horse run!
delete p; //Pegasus deconstructor! //Bird deconstructor! //Horse deconstructor! //Animal deconstructor! return 0; }
|
这样,Animal就不是由Horse和Bird初始化,而是由Pegasus初始化。Horse和Bird必须在它们的构造函数内初始化Animal,但当创建一个Pegasus对象时,这些初始化将被忽略。
为了确保派生类只有公共基类的一个实例,把中间类声明为从基类的虚继承。
如:
class Horse: virtual public Animal
class Bird: virtual public Animal
class Pegasus: public Horse, public Bird
阅读(763) | 评论(0) | 转发(0) |