C++ //继承同名成员处理方式

 1 #include <iostream>
 2 #include <string>
 3 using namespace std;
 4 
 5 class Base
 6 {
 7 public:
 8     Base()
 9     {
10         m_A = 100;
11     }
12     void func()
13     {
14         cout << "Base -func()调用" << endl;
15     }
16     int m_A;
17 
18     void func(int a)
19     {
20         cout << "Base -func(int a)调用" << endl;
21     }
22 
23 
24 };
25 
26 class Son : public Base
27 {
28 public:
29     Son()
30     {
31         m_A = 200;
32     }
33 
34     void func()
35     {
36         cout << "Son -func()调用" << endl;
37     }
38 
39     void func(int a)
40     {
41         cout << "Son -func(int a)调用" << endl;
42     }
43 
44 
45     int m_A;
46 };
47 
48 //同名成员属性处理
49 void test01()
50 {
51     Son s;
52     cout << "Son m_A= " << s.m_A << endl;
53     //Base b;
54     //如果通过子类对象 访问到父类中的同名对象 要在子类后面加 父类的作用域
55     cout << "Base m_A= " << s.Base::m_A << endl;
56     //cout << "Base m_A= " << b.m_A << endl;
57 }
58 
59 //同名成员函数处理
60 void test02()
61 {
62     Son s;
63     s.func();  //直接调用的是: 子类用的同名成员
64 
65     //如何调用父类中的同名函数
66     s.Base::func();
67 
68     //如果子类出现和父类中的同名的成员函数 子类的同名成员会隐藏掉
69     //父类中所有的同名成员函数
70 
71     //如果想访问到父类中被隐藏的同名成员函数 需要加作用域
72     s.func(100);
73     s.Base::func(200);
74 
75 }
76 int main()
77 {
78 
79     //test01();
80     test02();
81 
82     system("pause");
83 
84     return 0;
85 
86 }

 

posted on 2021-08-08 10:35  Bytezero!  阅读(42)  评论(0编辑  收藏  举报