整理摘自https://blog.csdn.net/ithomer/article/details/6031329
1. 申明格式
class CShape { public: virtual void Show()=0; };
在普通的虛函數后面加上"=0"這樣就聲明了一個pure virtual function.
2. 何時使用純虛函數?
3. 舉例說明
(1)不可實例化含有虛函數的基類
我們來舉個例子,我們先定義一個形狀的類(Cshape),但凡是形狀我們都要求其能顯示自己。所以我們定義了一個類如下:
class CShape { virtual void Show(){}; };
但沒有CShape這種形狀,因此我們不想讓CShape這個類被實例化,我們首先想到的是將Show函數的定義(實現)部分刪除如下:
class CShape { virtual void Show(); };
class CShape
{ public: virtual void Show()=0; };
當實例化CShape cs 后,會報錯:
error: cannot declare variable ‘cs’ to be of abstract type ‘CShape’
CShape cs;
^
note: because the following virtual functions are pure within ‘CShape’:
class CShape
^
note: virtual void CShape::Show()
virtual void Show()= 0;
^
(2)派生類中堆基類中虛函數的實現
class CShape { public: virtual void Show()= 0; }; class CPoint2D: public CShape { public: void Msg() { printf("CPoint2D.Msg() is invoked.\n"); } /* void Show() { printf("Show() from CPoint2D.\n"); } */ };
當實例化 CPoint2D p2d時,報錯
error: cannot declare variable ‘p2d’ to be of abstract type ‘CPoint2D’
CPoint2D p2d;
^
note: because the following virtual functions are pure within ‘CPoint2D’:
class CPoint2D: public CShape
^
note: virtual void CShape::Show()
virtual void Show()= 0;
^
我們預防了在派生類中忘記實現基類方法。如果不在派生類的中實現在Show方法,編譯都不會通過。
以下為完整代碼:
#include <iostream> #include <cstdio> using namespace std; class CShape { public: virtual void Show()= 0; }; class CPoint2D: public CShape { public: void Msg() { printf("CPoint2D.Msg() is invoked.\n"); } void Show() { printf("Show() from CPoint2D.\n"); } }; int main() { CPoint2D p2d; p2d.Msg(); CPoint2D *pShape = &p2d; pShape -> Show(); return 0; } /* Output: CPoint2D.Msg() is invoked. Show() from CPoint2D. */