1. 程式人生 > >【C++】重定義,過載,重寫

【C++】重定義,過載,重寫

過載

同一個作用域內,方法名相同而引數不同的幾個方法。

class AA
{
public:
    void print()
    {
        cout << "父類" << endl;
    }
    void print(int x )
    {
        cout << "父類:" << x  << endl;
    }
};

重寫

函式特徵相同。但是具體實現不同,主要是在類繼承關係中出現的 。當我們對別人提供好的類的方法感覺不是太滿意時,我們就可以通過繼承這個類然後重寫其方法改成我們需要的邏輯。

1、最重要的一點,重寫是子類與父類之間的。

2、被重寫的函式不能是 static 的。

3、函式三要素(函式名、函式引數、函式返回型別)完全一樣。

4、如果父類中有virtual關鍵字,這種父子之間的關係叫做虛擬函式重寫,這也就是C++中的多型機制。

class AA
{
public:
    virtual void print(int x )
    {
        cout << "父類:" << x  << endl;
    }
};

class BB : public AA
{
public:
    virtual void print(int x)
    {
        cout << "子類:" << x  << endl;
    }
};

int main()
{
    AA *p = NULL;
    BB b; 
    p = &b;
    p->print(1);
}

重定義

重定義 (redefining)也叫做隱藏:

子類重新定義父類中有相同名稱的非虛擬函式 ( 引數列表可以不同 ) 。

class AA
{
public:
    void print()
    {
        cout << "父類" << endl;
    }
};
class BB : public AA
{
public:
    void print(int x)//這叫重定義,此時A類中的print()被隱藏
    {
        cout << "子類:" << x  << endl;
    }
};

void main()
{
    int x = 1;
    BB b; //子類
    AA a; //父類
    a.print();//訪問父類的print()
    b.print(x);//訪問子類的print()
    b.AA::print();//訪問父類的print()
    //b.print();error:函式引數太少
}

這種情況下print()和print(int x)叫作重定義,在重定義時,父類的print()方法被隱藏了,要想使用父類的方法必須通過::。

關於重定義補充一點:由於在同一個作用域內,C++不允許出現相同命名的函式或變數,所以如果你出現了重複,就會報重定義錯誤。