所謂同名成員也就是 子類與父類 變量或者成員函數重名
看看以下代碼,了解訪問方式
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.子類中的同名函數會隱藏父類的同名函數,調用時要加作用域