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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值