虚基类的好处

先来对比一下用虚基类和不用虚基类的区别

#include<iostream>
using namespace std;
class Base{
public:
 Base(){
  a=5;
  cout<<"Base a="<<a<<endl;
 }
protected:
 int a;
};
class Base1:public Base{
public:
 Base1(){
  a=a+10;
  cout<<"Base1 a="<<a<<endl;
 }
};
class Base2:public Base{
public:
 Base2(){
  a=a+20;
  cout<<"Base2 a="<<a<<endl;
 }
};
class Derived:public Base1,public Base2{
public:
 Derived(){
  cout<<"Base1::a="<<Base1::a<<endl;
  cout<<"Base2::a="<<Base2::a<<endl;//如果不用域操作符,不知道调用谁的a,是Base1还是Base2?
 }
};
int main(){
 Derived obj;
 system("pause");
 return 0;
}

结果:

虚基类的好处_第1张图片

 

层次结构图:

虚基类的好处_第2张图片

下面是使用了虚基类的

#include<iostream>
using namespace std;
class Base{
public:
 Base(){
  a=5;
  cout<<"Base a="<<a<<endl;
 }
protected:
 int a;
};
class Base1:virtual public Base{
public:
 Base1(){
  a=a+10;
  cout<<"Base1 a="<<a<<endl;
 }
};
class Base2:virtual public Base{
public:
 Base2(){
  a=a+20;
  cout<<"Base2 a="<<a<<endl;
 }
};
class Derived:public Base1,public Base2{
public:
 Derived(){
  cout<<"Derived a="<<a<<endl;//这里不用使用域操作符,因为虚基类实现了数据共享
 
 }
};
int main(){
 Derived obj;
 system("pause");
 return 0;
}

结果:

  
虚基类的好处_第3张图片
层次结构图:
虚基类的好处_第4张图片
相信你已经知道了虚基类的好处了吧,虚基类实现了共享共同基类的数据
 

你可能感兴趣的:(Class)