怎样使用C语言实现C++的多态?
这是我接受豌豆荚面试时考官问到的一道题,我当初没有回答上来,因为之前从来没有考虑过这种问题。
下面的内容是转载的一篇博客,点此查看原文。
就拿传统的圆与正方形问题为例子,基类是Shape,每个类定义虚函数showShape(),从而体现多态。
大概思想就是每个结构体头都一样(当作某个基类),这样可以用结构体头指针指向任何结构体,虚函数就是在这个结构体头上做文章,看代码吧,注释写得很详细。
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
|
#include <malloc.h>
#include <stdio.h>
//定义2个类型意思一下
enum
ShapeType {CIRCLE, SQUARE};
//虚函数表里的两个函数,calculate也是意思一下,无意义
typedef
void
(*show)();
typedef
double
(*calculate)(
int
arg);
//虚函数表结构体
typedef
struct
_VirtualFun
{
show showShape;
calculate calArea;
} VirtualFun,*pVirtualFun;
//基类,Shape
typedef
struct
_Shape
{
ShapeType type;
VirtualFun *pfun;
}Shape,*ShapePointer;
//派生类,Circle
typedef
struct
_Circle
{
Shape itsType;
int
r;
}Circle;
//派生类,Square
typedef
struct
_Square
{
Shape itsType;
int
d;
}Square;
//重写的虚函数
void
showCircle()
{
printf
(
"I'm circle\n"
);
}
//重写的虚函数
void
showSquare()
{
printf
(
"I'm square\n"
);
}
//circle初始化
Circle circle ={
CIRCLE,
(pVirtualFun)
malloc
(
sizeof
(VirtualFun)),
0
};
//square初始化
Square square ={
SQUARE,
(pVirtualFun)
malloc
(
sizeof
(VirtualFun)),
0
};
//测验多态,只需要传递基类指针ShapePointer。
void
virtualShow(ShapePointer sp)
{
sp->pfun->showShape();
}
void
main()
{
//虚函数初始化
circle.itsType.pfun->showShape = showCircle;
square.itsType.pfun->showShape = showSquare;
//用基类指针指向派生类
ShapePointer spc = (ShapePointer)&circle;
ShapePointer sps = (ShapePointer)□
//传递基类指针,体现多态。
virtualShow(spc);
virtualShow(sps);
getchar
();
}
|
输出结果:
I'm circle I'm square