[C++基礎] 純虛函數


整理摘自https://blog.csdn.net/ithomer/article/details/6031329

1. 申明格式

class CShape
{
public:
    virtual void Show()=0;
};

在普通的虛函數后面加上"=0"這樣就聲明了一個pure virtual function.

2. 何時使用純虛函數?

(1)當想在基類中抽象出一個方法,且該基類只做能被繼承,而不能被實例化;
(2)這個方法必須在派生類(derived class)中被實現;
  如果滿足以上兩點,可以考慮將該方法申明為pure virtual function.

3. 舉例說明

(1)不可實例化含有虛函數的基類

我們來舉個例子,我們先定義一個形狀的類(Cshape),但凡是形狀我們都要求其能顯示自己。所以我們定義了一個類如下:

class CShape
{
    virtual void Show(){};
};

但沒有CShape這種形狀,因此我們不想讓CShape這個類被實例化,我們首先想到的是將Show函數的定義(實現)部分刪除如下:

class CShape
{
    virtual void Show();
};
當我們使用下面的語句實例化一個CShape時:
CShape cs;  //這是我們不允許的,但僅用上面的代碼是可以通過編譯(但link時失敗)。
 
怎樣避免一個CShape被實例化,且在編譯時就被發現?
答案:  使用pure virtual function.
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)派生類中堆基類中虛函數的實現

        我們再來看看被繼承的情況,我們需要一個CPoint2D的類,它繼承自CShape.它必須實現基類(CShape)中的Show()方法。
        其實使用最初的本意是讓 每一個派生自CShape的類,都要實現Show()方法,但時常我們可能在一個派生類中忘記了實現Show(),為了避免這種情況,pure virtual funcion發揮作用了。
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.
*/

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM