C++中继承中的同名成员问题

来源:互联网 发布:淘宝捡漏类小说 编辑:程序博客网 时间:2024/05/16 05:07

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>
 
usingnamespace std;
 
classA{
public:
    inta;
    A(){
        a = 1;
    }
     
    intget_a(){
        returna;
    }
 
    voidprint(){
        cout <<"This is A. a: " << a << endl;
    }
};
 
classB: public A{
public:
    inta;
    B(){
        a = 2;
    }
 
    voidprint(){
        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();
    return0;
}

 输出结果为:

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

0 0
原创粉丝点击