C++虚基类的作用及使用1

来源:互联网 发布:php编译安装5.6.31 编辑:程序博客网 时间:2024/05/20 10:11

一.虚基类的何时使用:

如下程序所示,当son类,继承father类和mother类,并且father类继承自human类,mother也继承自human类.此时当son类对象调用human类中的公有变量或函数时,就要使用虚基类.由于son类直接继承自father类和mother类,而father类和mother类又继承自human类.所以son对象是理论上可以调用human这个基类成员的(含变量和函数). 由于father类和mother类都继承了human类,因此human类中的公有成员就被这2个类分别继承,这时son类继承father类和mother类,就说明son类通过2种途径继承了来自human类的成员.当我们引用son对象调用human类成员时,会出现通过father类继承调用了human类成员,同时也出现通过mother类继承调用了human类成员.这时编译器蒙圈了.它不知道怎么调用了.如下边代码的son1.bb这种调用.这个bb到底是通过father类继承调用human类的bb呢?还是通过mother类继承调用human类的bb呢?因此需要使用关键字virtual来定义虚基类.本例子的虚基类为human类.

二.虚基类的好处:

当发送上述情况时,由于将human类为虚基类,因此father类和mother类就会只有一方继承human类的成员,具体是father类还是mother类继承它的成员,这是编译器决定的.这个不追究.我们放在下边的重点上.这时son对象引用human类的成员,编译器就知道了是father类继承了human类的bb,或者是mother类继承了human类的bb,当然father类和mother类要取其一.这就不会出现错误.在"一.虚基类何时使用"时,提到"编译器不知道:son对象到底是通过father类继承的human类成员bb,还是通过mother类继承的human类成员bb."这里编译器就知道了:到底是哪一个类(这里指father类或mother类)引用了human类的成员bb.就不会出现不知道father类和mother类继承human类的bb的情况.这种歧义叫"两义性".为了好理解我们看下边的代码吧.

  1. class human  
  2.  {  
  3.  public:  
  4.      int bb;//这是虚基类演示的成员bb.  
  5.   
  6.  };  
  7.  class father :  
  8.         public  human  
  9.  {  
  10.  public:  
  11.   
  12.  };  
  13.  class mother :   
  14.         public  human  
  15.  {  
  16.  public:  
  17.   
  18.  };  
  19.   
  20.  class son :  
  21.          public mother,  public father  
  22.  {  
  23.   
  24.  };  
  25.   
  26.   
  27. int _tmain(int argc, _TCHAR* argv[])  
  28. {  
  29.       
  30.     son son1;  
  31.     son1.bb=1;//此处不使用虚基类时会出现错误.因为无法知道是通过father类继承得到的bb,还是mother继承得到的bb.  
  32. system("pause");  
  33.   
  34.     return 0;  
  35. }  

这是vs2013错误提示:


这是使用了虚基类的代码,可以正常编译并使用.

  1.  class human  
  2.  {  
  3.  public:  
  4.      int bb;//这是虚基类演示的成员bb.  
  5.     void stand(){ cout << "human类输出"; }  
  6.  };  
  7.  class father :  
  8.      virtual    public  human  
  9.  {  
  10.  public:  
  11.   
  12.  };  
  13.  class mother :   
  14.      virtual    public  human  
  15.  {  
  16.  public:  
  17.   
  18.  };  
  19.   
  20.  class son :  
  21.          public mother,  public father  
  22.  {  
  23.   
  24.  };  
  25.   
  26.   
  27. int _tmain(int argc, _TCHAR* argv[])  
  28. {  
  29.       
  30.     son son1;  
  31.     son1.bb=1;//此处不使用虚基类时会出现错误.因为无法知道是通过father类继承得到的bb,还是mother继承得到的bb.  
  32.     son1.stand();  
  33. system("pause");  
  34.   
  35.     return 0;  
  36. }
从中可以看出,虚基类,主要是在 第一基类 派生 出第二基类,第二基类派生出派生类,这个派生类要使用第一基类的成员,这时候才使用虚基类.

0 0
原创粉丝点击