c++继承中同名成员处理

所谓同名成员也就是 子类与父类 变量或者成员函数重名

看看以下代码,了解访问方式

 1 #include<bits/stdc++.h>
 2 using namespace std;
 3 
 4 class father
 5 {
 6 public:
 7     int a = 100;
 8     void fun()
 9     {
10         cout << "father fun " << endl;
11     }
12     void fun(int x)
13     {
14         a = x;
15         cout << a << endl;
16     }
17 protected:
18     int b;
19 private:
20     int c;
21 };
22 
23 class son1:public father
24 {
25 public:
26     void fun()
27     {
28         cout << "son1 fun " << endl;
29     }
30     int a = 200;//同名变量
31 };
32 
33 void test01()
34 {
35     son1 s1;
36     cout << s1.a << endl;//这是子类的a输出是200
37 
38     cout << s1.father::a << endl;//这是父类的a输出100,访问是需要作用域
39 }
40 
41 //接下来看看同名成员函数
42 void test02()
43 {
44     son1 s1;
45     //和上面一样的
46     s1.fun();
47     s1.father::fun();
48     //s1.fun(110);是不允许的非法的因为子类的同名函数会隐藏父类的同名函数
49     s1.father::fun(110);
50 }
51 int main()
52 {
53     //test01();
54     test02();
55     return 0;
56 }

我们可以得出结论

1.子类可以直接访问子类中的同名成员

2.子类可以通过添加作用域来访问父类中的同名成员

3.子类中的同名函数会隐藏父类的同名函数,调用时要加作用域

原文地址:https://www.cnblogs.com/mch5201314/p/11594193.html