1. 程式人生 > >c++中重載,重寫,覆蓋

c++中重載,重寫,覆蓋

space round 個數 屏蔽 double same esp 基類 turn

1.重載

重載從overload翻譯過來,是指同一可訪問區內被聲明的幾個具有不同參數列表(參數的類型,個數,順序不同)的同名函數,根據參數列表確定調用哪個函數,重載不關心函數返回類型。

  1. 相同的範圍(在同一個作用域中)
  2. 函數名字相同
  3. 參數不同列表
  4. virtual 關鍵字可有可無
  5. 返回值可以不同
int test();
int test(int a);
int test(int a,double b);
int test(double a,int a);
int test(string s);
...

3.重寫

  重寫翻譯自override,是指派生類中存在重新定義的函數。其函數名,參數列表,返回值類型,所有都必須同基類中被重寫的函數一致

。只有函數體不同(花括號內),派生類調用時會調用派生類的重寫函數,不會調用被重寫函數。重寫的基類中被重寫的函數必須有virtual修飾

  1. 不在同一個作用域(分別位於派生類與基類)
  2. 函數名字相同
  3. 參數相同列表(參數個數,兩個參數列表對應的類型)
  4. 基類函數必須有 virtual 關鍵字,不能有 static,大概是多態的原因吧...
  5. 返回值相同(或是協變),否則報錯
  6. 重寫函數的訪問修飾符可以不同。盡管 virtual 是 private 的,派生類中重寫改寫為 public,protected 也是可以的
class Base
{
    public:
        void test(int
a) { cout<<"this is base"<<endl; } }; class Ship:public Base { public: void test(int a) { cout<<"this is Base overwrite function"<<endl; } };

3.隱藏

  隱藏是指派生類的函數屏蔽了與其同名的基類函數。註意只要同名函數,不管參數列表是否相同,基類函數都會被隱藏

  1. 不在同一個作用域(分別位於派生類與基類)
  2. 函數名字相同
  3. 返回值可以不同
  4. 參數不同,此時,論有無virtual關鍵字,基類的函數將被隱藏(註意別與重載混淆)而不是被重寫
  5. 參數相同,但是基類函數沒有virtual關鍵字。此時,基類的函數被隱藏(註意別與覆蓋混淆)
#include <iostream>
using namespace std;

class Base
{
    public:
        virtual void test(int a)//有virtual關鍵字,參數列表不同 
        {
            cout<<"this is base there are different parameters with virtual"<<endl;
        }
        
        void test1() 
        {
            cout<<"this is base with the same parameters with not virtual"<<endl;
        }
        
         virtual void test2() 
        {
            cout<<"this is base with the same parameters with virtual"<<endl;
        }
};

class Ship:public Base
{
    public:
        void test()
        {
            cout<<"this is Ship there are different parameters with virtual cover"<<endl;
        }
        
        void test1() 
        {
            cout<<"this is Ship with the same parameters with not virtual cover"<<endl;
        }
        
        void test2() 
        {
            cout<<"this is Ship with the same parameters with virtual cover"<<endl;
        }
};

int main()
{
    Ship s;
    s.test();
    s.test1();
    s.test2();
    return 0;
}

區別

重載和重寫的區別

  1. 範圍區別:重寫和被重寫的函數在不同的類中,重載和被重載的函數在同一類中。
  2. 參數區別:重寫與被重寫的函數參數列表一定相同,重載和被重載的函數參數列表一定不同。
  3. virtual的區別:重寫的基類必須要有virtual修飾,重載函數和被重載函數可以被virtual修飾,也可以沒有。

隱藏和重寫,重載的區別

  1. 與重載範圍不同:隱藏函數和被隱藏函數在不同類中。
  2. 參數的區別:隱藏函數和被隱藏函數參數列表可以相同,也可以不同,但函數名一定同;當參數不同時,無論基類中的函數是否被virtual修飾,基類函數都是被隱藏,而不是被重寫。

c++中重載,重寫,覆蓋