虛函數、純虛函數詳解

1.首先:強調一個概念 
       定義一個函數爲虛函數,不代表函數爲不被實現的函數。定義他爲虛函數是爲了允許用基類的指針來調用子類的這個函數。
       定義一個函數爲純虛函數,才代表函數沒有被實現。定義他是爲了實現一個接口,起到一個規範的作用,規範繼承這個。類的程序員必須實現這個函數。 

2.關於實例化一個類: 
有純虛函數的類是不可能生成類對象的,如果沒有純虛函數則可以。比如: 
class CA 

public: 
    virtual void fun() = 0;  // 說明fun函數爲純虛函數 
    virtual void fun1(); 
}; 

class CB 

public: 
   virtual void fun(); 
   virtual void fun1(); 
}; 

// CA,CB類的實現 
... 

void main() 

    CA a;   // 不允許,因爲類CA中有純虛函數 
    CB b;   // 可以,因爲類CB中沒有純虛函數 
    ... 


3.虛函數在多態中間的使用: 
   多態一般就是通過指向基類的指針來實現的。 

4.有一點你必須明白,就是用父類的指針在運行時刻來調用子類: 
例如,有個函數是這樣的: 
void animal::fun1(animal *maybedog_maybehorse) 

     maybedog_maybehorse->born();

參數maybedog_maybehorse在編譯時刻並不知道傳進來的是dog類還是horse類,所以就把它設定爲animal類,具體到運行時決定了才決定用那個函數。也就是說用父類指針通過虛函數來決定運行時刻到底是誰而指向誰的函數。

5.用虛函數 
#include <iostream.h> 

class animal 

public: 
     animal(); 
     ~animal(); 
     void fun1(animal *maybedog_maybehorse); 
     virtual void born(); 
}; 

void animal::fun1(animal *maybedog_maybehorse) 

     maybedog_maybehorse->born(); 
}

animal::animal() { } 
animal::~animal() { } 
void animal::born() 

     cout<< "animal"; 

///////////////////////horse
class horse:public animal 

public: 
     horse(); 
     ~horse(); 
     virtual void born(); 
}; 

horse::horse() { } 
horse::~horse() { } 
void horse::born()

     cout<<"horse"; 

///////////////////////main
void main() 

     animal a; 
     horse b; 
     a.fun1(&b); 


//output: horse

6.不用虛函數 
#include <iostream.h> 
class animal 

public: 
     animal(); 
     ~animal(); 
     void fun1(animal *maybedog_maybehorse); 
     void born(); 
}; 

void animal::fun1(animal *maybedog_maybehorse) 

     maybedog_maybehorse->born(); 


animal::animal() { }
animal::~animal() { } 
void animal::born() 

     cout<< "animal"; 

////////////////////////horse
class horse:public animal 

public: 
     horse(); 
     ~horse(); 
     void born(); 
}; 

horse::horse() { } 
horse::~horse() { } 
void horse::born()

     cout<<"horse"; 

////////////////////main
void main() 

     animal a; 
     horse b; 
     a.fun1(&b); 

//output: animal

發佈了22 篇原創文章 · 獲贊 13 · 訪問量 12萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章