虚继承和虚基类

来源:互联网 发布:linux配置nginx 编辑:程序博客网 时间:2024/06/05 17:36

虚继承主要解决在多重继承中的菱形继承问题,也就是说 B和C类同时继承了A类,然后D类继承了B,C类,那么D类的虚表就会有重复的函数指针。

#include<iostream>using namespace std;//虚基类class Person{    public:        Person(){cout<<"Person()"<<endl;}        ~Person(){cout<<"~Person()"<<endl;}        Person(string name)        //  :name(name) //3.3 error        {            cout<<"Person(string)"<<endl;        }        void talk()        {            cout<<"i'm person"<<endl;        }    protected:        string name;};class Mother:virtual public Person//虚继承{    public:        Mother(){cout<<"Mother()"<<endl;}        ~Mother(){cout<<"~Mother()"<<endl;}        Mother(string name)        //  :Person(name) //3.2        {            cout<<"Mother(string)"<<endl;        }        void talk()        {            cout<<"i'm mother"<<endl;        }        void cook()        {            cout<<"cooking"<<endl;        }};class Father:virtual public Person//虚继承{    public:        Father(){cout<<"Father()"<<endl;}        ~Father(){cout<<"~Father()"<<endl;}        Father(string name)        //  :Person(name) //3.2        {            cout<<"Father(string)"<<endl;        }        void talk()        {            cout<<"i'm Father"<<endl;        }        void repair()        {            cout<<"repairing"<<endl;        }};class Child:public Father, public Mother{    public:        Child(){cout<<"Child"<<endl;}        ~Child(){cout<<"~child"<<endl;}        Child(string name)            //:name(name) //2.error            //:Father(name), Mother(name) //3.1            //Person(name); //4.ok        {            this->name=name;//1.ok            cout<<"Child(string)"<<endl;        }        void talk()        {            cout<<"i'm child"<<endl;            cout<<"my name is name "<<name<<endl;        }};main(){    Child child("jack");    child.cook();    child.repair();    child.talk();}
原创粉丝点击