C++中的覆盖和隐藏

论坛 期权论坛 脚本     
匿名技术用户   2021-1-5 22:18   18   0

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

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

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


再给出隐藏的特征:

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

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

输出为


若代码处像下面这样的,

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

则是覆盖,输出为:

分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:7942463
帖子:1588486
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP