虚继承主要解决在多重继承中的菱形继承问题,也就是说 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();
}