虚基类的作用是为了避免派生类从基类中继承过来的同名成员同时产生多个副本。
图解:
祖父类->两个父亲类-》一个孩子类
#include<iostream>
using namespace std;
class base0{
public:
int var0;
void fun0(){cout<<"member of baseo"<<endl;}
};
class base1:virtual public base0{
public:
int var1;
};
class base2:virtual public base0{
public :
int var2;
};
class base:public base1,public base2{
int var;
void fun(){cout<<"member of base"<<endl;}
};
int main(){
base bb;
bb.var0=2;
bb.fun0();
return 0;
}
不用虚基类时
#include<iostream>
using namespace std;
class base0{
public:
int var0;
void fun0(){cout<<"member of baseo"<<endl;}
};
class base1:public base0{
public:
int var1;
};
class base2:public base0{
public :
int var2;
};
class base:public base1,public base2{
int var;
void fun(){cout<<"member of base"<<endl;}
};
int main(){
base bb;
bb.base1::var0=2;
bb.base1::fun0();
bb.base2::var0=3;
bb.base2::fun0();
return 0;
}
多继承同名隐藏举例
如果某派生类的多个基类拥有同名的成员,同时,派生类又新增了这样的同名成员,在这种情况下,派生类的成员将隐藏所有基类的同名成员。
一个父亲-》两个孩子类
#include<iostream>
using namespace std;
class base1{
public:
int var;
void fun(){cout<<"member of bse1"<<endl;}
};
class base2{
public:
int var;
void fun(){cout<<"member of base2"<<endl;}
};
class base:public base1,public base2{
public:
int var;
void fun(){cout<<"member of base3"<<endl;}
};
int main(){
base bb;
base *mm=&bb;
bb.var=1;
bb.fun();
bb.base1::var=2;
bb.base1::fun();
mm->base2::var=3;
mm->base2::fun();
return 0;
}