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取了出来。这也就说明了,同名的成员变量相互独立,而同名的成员函数会发生覆盖。