C++ 重载(overload)与重写(覆盖)(override)

C++的重载(overload)与重写(override)

成员函数被重载的特征:
(1)相同的范围(在同一个类中);
(2)函数名字相同;
(3)参数不同;
(4)virtual关键字可有可无。

重写是指派生类函数重写基类函数,是C++的多态的表现,特征是:
(1)不同的范围(分别位于派生类与基类);
(2)函数名字相同;
(3)参数相同;
(4)基类函数必须有virtual关键字。

示例中,函数Base::f(int)与Base::f(float)相互重载,而Base::g(void)被Derived::g(void)重写。

#include <iostream>
using namespace std;


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


class Derived : public Base
{
public:
    virtual void g(void){ cout << "Derived::g(void)" << endl;}
};


int main()
{
    Derived  d;
    Base *pb = &d;
    pb->f(42);        // Base::f(int) 42
    pb->f(3.14f);     // Base::f(float) 3.14
    pb->g();          // Derived::g(void)


    return 0;

}

这里“隐藏”是指派生类的函数屏蔽了与其同名的基类函数,规则如下:
(1)如果派生类的函数与基类的函数同名,但是参数不同。此时,不论有无virtual关键字,基类的函数将被隐藏。
(2)如果派生类的函数与基类的函数同名,并且参数也相同,但是基类函数没有virtual关键字。此时,基类的函数被隐藏。
这种隐藏规则,不仅仅是表现在对成员函数上,对同名的data member也是如此。

示例程序中:
(1)函数Derived::f(float)重写了Base::f(float)。
(2)函数Derived::g(int)隐藏了Base::g(float)。
(3)函数Derived::h(float)隐藏了Base::h(float)。

#include <iostream>

using namespace std;

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) "<<endl;

}

};

class Derived:public Base

{

public:

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)"<<endl;

}

};

int main() {

Derived d;

Base *pb=&d;

Derived *pd=&d;

pb->f(3.14f);

pd->f(3.14f);

pb->g(3.14f);

pd->g(3.14f);

pb->h(3.14f);

pd->h(3.14f);

return 0;

}


函数的覆盖和隐藏

父类和子类出现同名函数称为隐藏。

  • 父类对象.函数函数名(...);     //调用父类的函数
  • 子类对象.函数名(...);           //调用子类的函数  
  • 子类对象.父类名::函数名(...);//子类调用从父类继承来的函数。

父类和子类出现同名虚函数称为覆盖

  • 父类指针=new 子类名(...);父类指针->函数名(...);//调用子类的虚函数。

猜你喜欢

转载自blog.csdn.net/qq_40213457/article/details/80663651
今日推荐