C++中的覆盖和隐藏

C++中的覆盖和隐藏,是个令人头疼的问题,下面写几点自己的认识。

首先,参考c++高质量编程指南,给出覆盖的特征:

覆盖是指派生类函数覆盖基类函数,特征是:
(1)不同的范围(分别位于派生类与基类);
(2)函数名字相同;
(3)参数相同
(4)基类函数必须有virtual 关键字


再给出隐藏的特征:

“隐藏”是指派生类的函数屏蔽了与其同名的基类函数,规则如下:
(1)如果派生类的函数与基类的函数同名,但是参数不同。此时,不论有无virtual
关键字
,(如果参数相同,基类有virtual,则是覆盖(按照覆盖的特征))基类的函数将被隐藏(注意别与重载混淆)。
(2)如果派生类的函数与基类的函数同名,并且参数也相同,但是基类函数没有virtual
关键字。此时,基类的函数被隐藏(注意别与覆盖混淆)。

[cpp]  view plain  copy
  1. #include<iostream>  
  2. using namespace std;  
  3.   
  4.   
  5. class Base  
  6. {  
  7. public:  
  8.     virtual void f(float x){ cout << "Base::f(float) " << x << endl; }  
  9.     void g(float x){ cout << "Base::g(float) " << x << endl; }  
  10.     void h(float x){ cout << "Base::h(float) " << x << endl; }  
  11. };  
  12.   
  13. class Derived : public Base  
  14. {  
  15. public:  
  16.     //virtual void f(float x){ cout << "Derived::f(float) " << x << endl; }//覆盖了基类的f  
  17.     virtual void f(int x){ cout << "Derived::f(int) " << x << endl; }//隐藏了基类的f  
  18.     void g(int x){ cout << "Derived::g(int) " << x << endl; }  
  19.     void h(float x){ cout << "Derived::h(float) " << x << endl; }  
  20. };  
  21.   
  22.   
  23. int main()  
  24. {  
  25.     Derived d;  
  26.     Base *pb = &d;  
  27.     Derived *pd = &d;  
  28.     // Good : behavior depends solely on type of the object//覆盖的情况  
  29.     pb->f(3.14f); // Derived::f(float) 3.14(覆盖)OR Base::f(float) 3.14(隐藏)  
  30.     pd->f(3.14f); // Derived::f(float) 3.14  
  31.     // Bad : behavior depends on type of the pointer  
  32.     pb->g(3.14f); // Base::g(float) 3.14  
  33.     pd->g(3.14f); // Derived::g(int) 3 (surprise!)  
  34.     // Bad : behavior depends on type of the pointer  
  35.     pb->h(3.14f); // Base::h(float) 3.14 (surprise!)  
  36.     pd->h(3.14f); // Derived::h(float) 3.14  
  37.     return 0;  
  38. }  

输出为


若代码处像下面这样的,

[cpp]  view plain  copy
  1. class Derived : public Base  
  2. {  
  3. public:  
  4.     virtual void f(float x){ cout << "Derived::f(float) " << x << endl; }//覆盖了基类的f  
  5.     //virtual void f(int x){ cout << "Derived::f(int) " << x << endl; }//隐藏了基类的f  
  6.     void g(int x){ cout << "Derived::g(int) " << x << endl; }  
  7.     void h(float x){ cout << "Derived::h(float) " << x << endl; }  
  8. };  

则是覆盖,输出为:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值