C++子类父类成员函数的覆盖和隐藏实例详解

时间:2022-04-11 08:09:29

C++子类父类成员函数的覆盖和隐藏实例详解

函数的覆盖

   覆盖发生的条件:

(1) 基类必须是虚函数(使用virtual 关键字来进行声明)
(2)发生覆盖的两个函数分别位于派生类和基类
(3)函数名和参数列表必须完全相同

函数的隐藏

    隐藏发生的条件:

(1)子类和父类的函数名相同,参数列表可以不一样

看完下面的例子就明白了

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#include "iostream"
using namespace std;
class CBase{
  public:
      virtual void xfn(int i){
          cout << "Base::xfn(int i)" << endl; //1
      }
      void yfn(float f){
          cout << "Base::yfn(float)" << endl; //2
      }
      void zfn(){
          cout << "Base::zfn()" << endl; //3
      }
};
class CDerived : public CBase{
  public:
      void xfn(int i){
        cout << "Derived::xfn(int i)" << endl; //4
      }
      void yfn(int c){
        cout << "Derived:yfn(int c)" << endl; //5
      }
      void zfn(){
        cout << "Derived:zfn()" << endl; //6
      }
};
void main(){
    CDerived d;
    CBase *pb = &d;
    CDerived *pd = &d;
    pb->xfn(5); //覆盖
    pd->xfn(5); //直接调用
 
    pb->yfn(3.14f); //直接调用
    pd->yfn(3.14f); //隐藏
 
    pb->zfn(); //直接调用
    pd->zfn(); //隐藏
}

C++子类父类成员函数的覆盖和隐藏实例详解

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

原文链接:http://blog.csdn.net/worldmakewayfordream/article/details/46827161