forked from Light-City/CPlusPlusThings
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathc_examp.c
More file actions
55 lines (44 loc) · 739 Bytes
/
c_examp.c
File metadata and controls
55 lines (44 loc) · 739 Bytes
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
54
55
/**
* @file c_examp.c
* @brief C实现多态
* @author 光城
* @version v1
* @date 2019-08-06
*/
#include <stdio.h>
/// 重定义一个函数指针类型
typedef void (*pf) ();
/**
* @brief 父类
*/
typedef struct _A
{
pf _f;
}A;
/**
* @brief 子类
*/
typedef struct _B
{
A _b; ///< 在子类中定义一个基类的对象即可实现对父类的继承。
}B;
void FunA()
{
printf("%s\n","Base A::fun()");
}
void FunB()
{
printf("%s\n","Derived B::fun()");
}
int main()
{
A a;
B b;
a._f = FunA;
b._b._f = FunB;
A *pa = &a;
pa->_f();
pa = (A *)&b; /// 让父类指针指向子类的对象,由于类型不匹配所以要进行强转
pa->_f();
return 0;
}