Chinaunix首页 | 论坛 | 博客
  • 博客访问: 162255
  • 博文数量: 30
  • 博客积分: 2010
  • 博客等级: 大尉
  • 技术积分: 290
  • 用 户 组: 普通用户
  • 注册时间: 2008-11-25 19:05
文章分类

全部博文(30)

文章存档

2009年(3)

2008年(27)

我的朋友

分类: C/C++

2008-12-06 19:50:00

    通常,一个类的构造函数只初始化自己的变量和基类。然而,虚继承的基类是一个例外。它们由它们的派生性最强的恶类初始化。
    有个继承关系如下:
   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) |
给主人留下些什么吧!~~