關於虛擬函數的一些總結 (參考:深入淺出MFC 第二版 候俊傑)

關於虛擬函數實現多態的總結:

 

1)如果希望在派生類別中重新定義父類的某個函數,則在父類中必須將此函數設爲虛擬函數;

 

2)抽象類別的虛擬函數一般不被調用,所以也不必被定義,將其設爲純虛函數;

 

3)在不使用虛擬函數的情況下,若用父類的指針指向某個派生類的對象,則使用該指針調用某個函數時,會調用指父類的函數;而使用虛擬函數,則會調用父類指針指向的派生類別的函數。因此,虛擬函數可以使得使用單一指令喚起不同函數,而非虛擬函數則只能根據指針的類型判斷調用哪個類中的函數;

 

4)擁有純虛擬函數的類別爲抽象類別,不可以有具體對象實例,但能申明該抽象類別的指針;

 

5)虛擬函數被繼承下去認爲虛擬函數,且可以省略關鍵字virtual;

 

6)虛擬函數是實現多態和動態綁定的關鍵。編譯器在編譯時,無法判斷究竟調用的是哪個虛擬函數,必須在執行的時候才能確定。

 

例子(摘自:深入淺出MFC 第二版 候俊傑):

  #0001 #include <iostream.h>
#0002 class CShape
#0003 {
#0004 public:
#0005 virtual void display() { cout << "Shape /n"; }
#0006 };
#0007 //------------------------------------------------
#0008 class CEllipse : public CShape
#0009 {
#0010 public:
#0011 virtual void display() { cout << "Ellipse /n"; }
#0012 };
#0013 //------------------------------------------------
#0014 class CCircle : public CEllipse
#0015 {
#0016 public:
#0017 virtual void display() { cout << "Circle /n"; }
#0018 };
#0019 //------------------------------------------------
#0020 class CTriangle : public CShape
#0021 {
#0022 public:
#0023 virtual void display() { cout << "Triangle /n"; }
#0024 };
不必設計複雜的串行函數如add 或getNext 才能驗證這件事,我們看看下面這個簡單例
子。如果我把職員一例中所有四個類別的computePay 函數前面都加上virtual 保留字,
使它們成爲虛擬函數,那麼:
現在重新回到Shape 例子,我打算讓display 成爲虛擬函數:
73
#0025 //------------------------------------------------
#0026 class CRect : public CShape
#0027 {
#0028 public:
#0029 virtual void display() { cout << "Rectangle /n"; }
#0030 };
#0031 //------------------------------------------------
#0032 class CSquare : public CRect
#0033 {
#0034 public:
#0035 virtual void display() { cout << "Square /n"; }
#0036 };
#0037 //------------------------------------------------
#0038 void main()
#0039 {
#0040 CShape aShape;
#0041 CEllipse aEllipse;
#0042 CCircle aCircle;
#0043 CTriangle aTriangle;
#0044 CRect aRect;
#0045 CSquare aSquare;
#0046 CShape* pShape[6] = { &aShape,
#0047    &aEllipse,
#0048    &aCircle,
#0049    &aTriangle,
#0050    &aRect,
#0051    &aSquare };
#0052
#0053 for (int i=0; i< 6; i++)
#0054 pShape[i]->display();
#0055 }
#0056 //------------------------------------------------
得到的結果是:
Shape
Ellipse
Circle
Triangle
Rectangle
Square

 

  

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章