編寫高品質代碼——區分Overloading、Overriding及Hiding之間的差異

來源:互聯網
上載者:User

■重載:同一範圍中,使用相同函數名,但是函數的參數個數或類型不同的函數。

例如:

#include <iostream>
using namespace std;
class printer{
    public :
        void print(int data){};
        void print(float data){};
        void print(const char& pStr, size_t size){};
        //other code
};
class stringPrinter:public printer{
    public :
        /* using printer::print; */   //將基類中的print 函式宣告引入到衍生類別的範圍中

        // 衍生類別的範圍中沒有print(int)的函數定義(被衍生類別中的print(const string&)隱藏)   
        void print(const string& str){};
        //other code
};
int main(){
    stringPrinter myPrinter;
    myPrinter.print(2011);
    return 0;
}

■重寫:在衍生類別中對基類中的虛函數重新實現,即衍生類別對基類虛函數的個人化定製。

Note:

1)函數的重寫與訪問層級(public、private、protected)無關(但是一般情況下,衍生類別重寫函數應和基類對應函數具有相同的訪問層級)

例如:

class CWorker{

public:

   virtual void Working(){ ... }

};

------------------------------------

class CDriver : public CWorker{

private :

   virtual void Working(){ ... ... }

};

2)const 可能會是虛成員函數的重寫失效(常量屬性是函數簽名中的一部分)

例如:

class CDriver : public CWorker{

private :

   virtual void Working() const{ ... }  //不會重寫基類的Working()函數

};

3)重寫函數必須和原函數具有相同的傳回型別(函數的傳回型別不是函數簽名的一部分,要求傳回型別必須相同)

例如:

class CDriver : public CWorker{

private :

   virtual bool Working() const{ ... }  //錯誤:重寫虛函數傳回型別有差異

};

■隱藏:衍生類別中的函數屏蔽基類中具有相同名字的非虛函數(調用類的成員函數時,編譯器會沿著類的繼承鏈逐級向上尋找函數的定義,如果找到就停止,即編譯器的函數尋找也就到達不了基類中,實現了隱藏)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.