欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

C++多繼承多態(tài)的實(shí)例詳解

 更新時(shí)間:2017年06月12日 17:12:29   投稿:lqh  
這篇文章主要介紹了C++多繼承多態(tài)的實(shí)例詳解的相關(guān)資料,需要的朋友可以參考下

C++多繼承多態(tài)的實(shí)現(xiàn)

如果一個(gè)類中存在虛函數(shù),在聲明類的對(duì)象時(shí),編譯器就會(huì)給該對(duì)象生成一個(gè)虛函數(shù)指針,該虛函數(shù)指針指向該類對(duì)應(yīng)的虛函數(shù)表。

多態(tài)的實(shí)現(xiàn)是因?yàn)槭褂昧艘环N動(dòng)態(tài)綁定的機(jī)制,在編譯期間不確定調(diào)用函數(shù)的地址,在調(diào)用虛函數(shù)的時(shí)候,去查詢虛函數(shù)指針?biāo)赶虻奶摵瘮?shù)表。

派生類生成的對(duì)象中的虛函數(shù)指針指向的是派生類的虛函數(shù)表,因此無論是基類還是派生來調(diào)用,都是查詢的是派生類的表,調(diào)用的是派生類的函數(shù)。

如果發(fā)生了多繼承,多個(gè)基類中都有虛函數(shù),那么該是怎樣的呢?虛函數(shù)指針如何排列,多個(gè)基類的指針為什么能夠同時(shí)指向派生類對(duì)象,同時(shí)發(fā)生多態(tài)?

請(qǐng)看下面這段程序

#include <stdio.h>
#include <iostream>
using namespace std;

class Base1{

  public:
  void fun()
  {
    printf("this is Base1 fun\n");
  }
  virtual void fun1()
  {
    printf("this is Base1 fun1\n");
  }
};

class Base2{
  public:
  void fun()
  {
    printf("this is Base2 fun\n");
  }
  virtual void fun2()
  {
    printf("this is Base2 fun1\n");
  }
};

class Derived : public Base1,public Base2{
  public:
  void fun()
  {
    printf("this is Derived fun\n");
  }
  void fun1()
  {
    printf("this is Derived fun1\n");
  }
  void fun2()
  {
    printf("this is Derived fun2\n");
  }
};

int main()
{
  Derived *pd = new Derived();
  Base1 *p1 = (Base1 *)pd;
  Base2 *p2 = (Base2 *)pd;
  p1->fun();
  p2->fun();
  p1->fun1();
  p2->fun2();
  printf("Base1 p1:%x\n", p1);
  printf("Base2 p2:%x\n", p2);
  return 0;
}

運(yùn)行結(jié)果如下

feng@mint ~/code/c++/cpp_muti_drived 
$ ./muti_derived 
this is Base1 fun
this is Base2 fun
this is Derived fun1
this is Derived fun2
Base1 p1:2097c20
Base2 p2:2097c28

Derived類分別繼承了Base1和Base2,根據(jù)結(jié)果來看,均發(fā)生了多態(tài)?;愔羔樥{(diào)用函數(shù),調(diào)用的均是派生類的對(duì)象。

通過打印出了p1和p2的地址,發(fā)現(xiàn)他們相差了8個(gè)字節(jié),就能明白了,在做類型轉(zhuǎn)換的過程中,如果把地址傳給第二個(gè)基類的指針的時(shí)候會(huì)自動(dòng)把地址減去8,在64位系統(tǒng)下,剛好是一個(gè)指針的長(zhǎng)度。因此p2指向的實(shí)際上是第二個(gè)虛函數(shù)指針的地址,這樣,就能夠?qū)崿F(xiàn)多繼承的多態(tài)了。

感謝閱讀,希望能幫助到大家,謝謝大家對(duì)本站的支持!

相關(guān)文章

最新評(píng)論