类的继承会首先寻找基类,若基类未实现,则会寻找派生类的函数
1. class继承,函数不继承
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
43
44
45
46
47
48
49
50
51
52
53
|
#include <stdio.h> class Base { public : Base(){} ~Base(){} int a; void setA() { a = 1; } }; class A: public Base { public : A(){} ~A(){} void setA() { a = 2; } }; class B: public Base { public : B(){} ~B(){} void setA() { a = 3; } }; int main() { A *ax = new A(); B *bx = new B(); Base *aClass = ax; Base *bClass = bx; aClass->setA(); bClass->setA(); printf ( "a value of a %d\n" , aClass->a); printf ( "a value of b %d\n" , bClass->a); return 0; } |
运行结果:
2. 函数和Class都继承
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
43
44
45
46
47
48
49
50
51
52
53
|
#include <stdio.h> class Base { public : Base(){} ~Base(){} int a; virtual void setA() { a = 1; } }; class A: public Base { public : A(){} ~A(){} virtual void setA() { a = 2; } }; class B: public Base { public : B(){} ~B(){} virtual void setA() { a = 3; } }; int main() { A *ax = new A(); B *bx = new B(); Base *aClass = ax; Base *bClass = bx; aClass->setA(); bClass->setA(); printf ( "a value of a %d\n" , aClass->a); printf ( "a value of b %d\n" , bClass->a); return 0; } |
运行结果:注意派生类中可以不写virtual,最好写上,以辨别是函数继承
若将2中基类的函数写为纯虚函数,运行的结果一样,但是如果基类是纯虚函数,派生类必须实现相应的函数。
1
2
3
4
5
6
7
8
9
10
|
class Base { public : Base(){} ~Base(){} int a; virtual void setA()=0; }; |
3. 类A中不有函数,则继承自基类
1
2
3
4
5
6
7
|
class A: public Base { public : A(){} ~A(){} }; |
结果为:
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。
原文链接:https://www.cnblogs.com/anlia/p/9083877.html