C++中重載(overload)、覆蓋(override)與隱藏(oversee)

來源:互聯網
上載者:User

標籤:類型   aac   diy   sea   bs4   nvl   不同   czc   iat   

重載、覆蓋與隱藏:
★對類層次中的同名成員函數來說,有3種關係:重載(overload)、覆蓋(override)和隱藏(hide、oversee),理清3種關係,有助於寫出高品質代碼。
重載: 重載的概念相對簡單,只有在同一類定義中的同名成員函數才存在重載關係,主要特點是函數的參數類型和數目有所不同,但不能出現函數參數的個數和類型均相同,僅僅依靠傳回值類型不同來區分的函數,這和普通函數的重載是完全一致的。另外,重載和成員函數是否是虛函數無關,舉例來說:
class A { …… virtual int fun(); void fun(int); void fun(double,double); …… }; 上述A類定義中的3個fun函數便是重載關係。

覆蓋:
★覆蓋是指:在衍生類別中覆蓋基類中的同名函數,要求兩個函數的參數個數、參數類型、傳回型別都相同,且 基類函數必須是虛函數
#include<iostream> using namespace std; class A {         public:                 virtual void fun1()                 {                         cout<<"A::fun1()"<<endl;                 }                 virtual void fun2()                 {                         cout<<"A::fun2()"<<endl;                 } }; class B:public A {         public:                 void fun1()  // B中的fun1覆蓋了A中的fun1,同時繼承了A中的fun2                 {                         cout<<"B::fun1()"<<endl;                 } }; class C:public B {         public:                 void fun2()                 {                         cout<<"C::fun2()"<<endl;  //C類繼承了B中的fun1,同時重定義覆蓋了fun2                 } }; int main() {         A* p = new C;         p->fun1();         p->fun2();         return 0; }



隱藏:
★隱藏指的是在某些情況下,衍生類別中的函數屏蔽了基類中的同名函數,這些情況包括:       ——2個函數參數相同,但基類函數不是虛函數。和覆蓋的區別在於基類函數是否是虛函數。       ——2個函數參數不同,無論基類函數是否是虛函數,基類函數都會被屏蔽。和重載的區別在於兩個函數不在同一類中。
#include <iostream> using namespace std; class A {         public:                 void fun(int xp)    //非虛函數,形參int                 {   cout<<xp<<endl;   } }; class B : public A {         public:         void fun(const char * s)  //隱藏,oversee,參數為字串 //參數相同,但是基類不是虛函數,構成隱藏oversee            {   cout<<s<<endl;   }         void fun(int xp)      //重載         {   cout<<"B::fun()"<<endl;   } }; int main() {         B b;         b.fun("hello");         b.fun(2);    //B 中沒有void fun(int) 會報錯,基類中的被覆蓋         return 0; }

C++中重載(overload)、覆蓋(override)與隱藏(oversee)

聯繫我們

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