C++中繼承中的同名成員問題

C++中,子類若有與父類同名的成員變量和成員函數,則同名的成員變量相互獨立,但同名的子類成員函數重載父類的同名成員函數。舉例如下:

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
40
41
42
#include <iostream>
 
using namespace std;
 
class A{
public:
    int a;
    A(){
        a = 1;
    }
     
    int get_a(){
        return a;
    }
 
    void print(){
        cout << "This is A. a: " << a << endl;
    }
};
 
class B: public A{
public:
    int a;
    B(){
        a = 2;
    }
 
    void print(){
        cout << "This is B. a: " << a << endl;
    }
};
 
int main(){
    A test1;
    B test2;
 
    cout << "test1.a: " << test1.get_a() << endl;
    test1.print();
    cout << "test2.a: " << test2.get_a() << endl;
    test2.print();
    return 0;
}

 輸出結果爲:

1
2
3
4
test1.a: 1
This is A. a: 1
test2.a: 1
This is B. a: 2

 爲什麼test2.get_a()中得到的a值爲1而非2呢?這是因爲類B中沒有get_a()這個函數,所以去其父類中找。找到這個函數後,依就近原則,把類A中的a給取了出來。而test2.print()調用的是類B中的print()函數,依就近原則,把類B中的a取了出來。這也就說明了,同名的成員變量相互獨立,而同名的成員函數會發生覆蓋。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章