C语言模拟C++虚函数多态性

怎样使用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)&square;
  
  //传递基类指针,体现多态。
  virtualShow(spc);
  virtualShow(sps);
  getchar ();
}

输出结果:

I'm circle
I'm square
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值