c++中的隱藏、重載、覆蓋(重寫)

來源:互聯網
上載者:User

 1 重載與覆蓋

    成員函數被重載的特徵:

(1)相同的範圍(在同一個類中);

(2)函數名字相同;

(3)參數不同;

(4)virtual關鍵字可有可無。 

    覆蓋是指衍生類別函數覆蓋基類函數,特徵是:

(1)不同的範圍(分別位於衍生類別與基類);

(2)函數名字相同;

(3)參數相同;

(4)基類函數必須有virtual關鍵字。

 

令人迷惑的隱藏規則
本來僅僅區別重載與覆蓋並不算困難,但是C++的隱藏規則使問題複雜性陡然增加。這裡“隱藏”是指衍生類別的函數屏蔽了與其同名的基類函數,規則如下:
(1)如果衍生類別的函數與基類的函數同名,但是參數不同。此時,不論有無virtual關鍵字,基類的函數將被隱藏(注意別與重載混淆)。
(2)如果衍生類別的函數與基類的函數同名,並且參數也相同,但是基類函數沒有virtual關鍵字。此時,基類的函數被隱藏(注意別與覆蓋混淆)。
上面的程式中:
(1)函數Derived::f(float)覆蓋了Base::f(float)。
(2)函數Derived::g(int)隱藏了Base::g(float),而不是重載。
(3)函數Derived::h(float)隱藏了Base::h(float),而不是覆蓋。

 

#include <iostream.h>    class Base{public:    virtual void f(float x){ cout << "Base::f(float) " << x << endl; }  void g(float x){ cout << "Base::g(float) " << x << endl; }  void h(float x){ cout << "Base::h(float) " << x << endl; }}; 


class Derived : public Base{public: virtual void f(float x){ cout << "Derived::f(float) " << x << endl; }  void g(int x){ cout << "Derived::g(int) " << x << endl; } void h(float x){ cout << "Derived::h(float) " << x << endl; }};

 

void main(void){    Derived d;    Base *pb = &d;   Derived *pd = &d;// Good : behavior depends solely on type of the object   pb->f(3.14f); // Derived::f(float) 3.14   pd->f(3.14f); // Derived::f(float) 3.14// Bad : behavior depends on type of the pointer   pb->g(3.14f); // Base::g(float) 3.14   pd->g(3.14f); // Derived::g(int) 3        (surprise!)// Bad : behavior depends on type of the pointer   pb->h(3.14f); // Base::h(float) 3.14      (surprise!)  pd->h(3.14f); // Derived::h(float) 3.14} 

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.