虚拟继承和虚基类

来源:互联网 发布:淘宝试用成功要付费吗 编辑:程序博客网 时间:2024/05/21 10:05
#include <iostream>using namespace std;class A{public:    A()    {        cout<< "this is A constructor"<<endl;    }    //needly    virtual ~A()    {        cout<<"this is A destructor"<<endl;    }    void Speak()    {        cout<<"this is A speak"<<endl;    }};class B1 : public virtual A{public:    B1()    {        cout<<"this is B1 constructor"<<endl;    }    ~B1()    {        cout<<"this is B1 destructor"<<endl;    }};class B2 : public virtual A{public:    B2()    {        cout<<"this is B2 constructor"<<endl;    }    ~B2()    {        cout<<"this is B2 destructor"<<endl;    }};class C: public B1,public B2{public:    C()    {        cout<<"this is C constructor"<<endl;    }    ~C()    {        cout<<"this is C destructor"<<endl;    }};int main(){    C *p = new C();    p->Speak();    delete p;    p = NULL;    return 0;}

执行结果:
this is A constructor
this is B1 constructor
this is B2 constructor
this is C constructor
this is A speak
this is C destructor
this is B2 destructor
this is B1 destructor
this is A destructor

虚拟继承即在继承时再基类前面加一个virtual关键字,而虚基类便是A。
通过虚继承我们可以解决三个问题:
存储问题:因为当非虚继承时,类C的内存中,将会产生两份类A的拷贝。
效率问题:非虚继承时,基类的构造(析构)函数被调用两次。
编译问题:调用基类的成员函数时会产生二义性,如这里的Speak(),当非虚继承时,B1跟B2均会继承A的Speak()成员函数,那么当子类C调用时将产生二义性,虽然可用::指定,但这不符合设计原则跟开发原则。

0 0
原创粉丝点击