【C/C++】重载、重写(覆盖)与隐藏

基本概念
  重载:是指同一可访问区内被声明的几个具有不同参数列(参数的类型,个数,顺序不同)的同名函数,根据参数列表确定调用哪个函数,重载不关心函数返回类型。
  重写(覆盖):是指派生类中存在重新定义的函数。其函数名,参数列表,返回值类型,所有都必须同基类中被重写的函数一致。只有函数体不同(花括号内),派生类调用时会调用派生类的重写函数,不会调用被重写函数。重写的基类中被重写的函数必须有virtual修饰。
  隐藏:是指派生类的函数屏蔽了与其同名的基类函数,注意只要同名函数,不管参数列表是否相同,基类函数都会被隐藏。

返回类型 参数 说明 范围
重载 无关 (类型、个数、顺序)必须不同 是指同一可访问区内的同名函数 同一类中
重写(覆盖) 相同 相同 是指派生类重新定义了基类中的同名函数 派生类与基类
隐藏 无关 无关 派生类屏蔽了基类的同名函数,只要同名就会隐藏 派生类与基类

参考博客:C++中重载、重写(覆盖)和隐藏的区别

重载

class A{
public:
  void test(int i);
  void test(double i);//overload
  void test(int i, double j);//overload
  void test(double i, int j);//overload
  int test(int i);         //错误,非重载。注意重载不关心函数返回类型。
};

重写(覆盖)

class Base
{
public:
    virtual void fun(int i){ cout << "Base::fun(int) : " << endl;}
    //必须要有virtual
};

class Derived : public Base
{
public:
    virtual void fun(int i){ cout << "Derived::fun(int) : " << endl;}
};
int main()
{
    Base * pb = new Derived();
    pb->fun(3);//Derived::fun(int)

    return 0;
}

隐藏

class Base
{
public:
    void fun(double ,int ){ cout << "Base::fun(double ,int )" << endl; }
};

class Derived : public Base
{
public:
    void fun(int ){ cout << "Derived::fun(int )" << endl; }
};

int main()
{
    Derived pd;
    pd.fun(1);//Derived::fun(int )
    pb.fun(0.01, 1);//error C2660: “Derived::fun”: 函数不接受 2 个参数

    return 0;
}

一个例子:

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; }
};

int 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

    // Bad : behavior depends on type of the pointer
    pb->h(3.14f); //Base::h(float) 3.14
    pd->h(3.14f); //Derived::h(float) 3.14

    return 0;
}

(1)函数Derived::f(float)重写(覆盖)了Base::f(float)。

(2)函数Derived::g(int)隐藏了Base::g(float)。

(3)函数Derived::h(float)隐藏了Base::h(float),重写(覆盖)基类被重写函数要加virtual。

猜你喜欢

转载自blog.csdn.net/ananbei/article/details/80972384