c++中的隐藏、重载、覆盖(重写)


重载------->同一个类中

隐藏-------->子类重写父类的非虚函数,或者是函数名相同,参数不同

覆盖(重写)---->重写父类的虚函数,参数相同。

 1 重载与覆盖
    成员函数被重载的特征:
(1)相同的范围(在同一个类中);
(2)函数名字相同;
(3)参数不同;
(4)virtual关键字可有可无。 
    覆盖是指派生类函数覆盖基类函数,特征是:
(1)不同的范围(分别位于派生类与基类);
(2)函数名字相同;
(3)参数相同;
(4)基类函数必须有virtual关键字。
令人迷惑的隐藏规则
本来仅仅区别重载与覆盖并不算困难,但是C++的隐藏规则使问题复杂性陡然增加。这里“隐藏”是指派生类的函数屏蔽了与其同名的基类函数,规则如下:
(1)如果派生类的函数与基类的函数同名,但是参数不同。此时,不论有无virtual关键字,基类的函数将被隐藏(注意别与重载混淆)。
(2)如果派生类的函数与基类的函数同名,并且参数也相同,但是基类函数没有virtual关键字。此时,基类的函数被隐藏(注意别与覆盖混淆)。
上面的程序中:
(1)函数Derived::f(float)覆盖了Base::f(float)。
(2)函数Derived::g(int)隐藏了Base::g(float),而不是重载。
(3)函数Derived::h(float)隐藏了Base::h(float),而不是覆盖。
复制代码
#include <iostream.h>
    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; }
}; 
void 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        (surprise!)
// Bad : behavior depends on type of the pointer
   pb->h(3.14f); // Base::h(float) 3.14      (surprise!)
  pd->h(3.14f); // Derived::h(float) 3.14

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值