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

看<Python源码剖析>有感,原来C语言可以这样玩。。仔细想想,C++不也是在汇编层面上的封装么。膜拜这些语言设计者,深谙计算机科学的精髓,真是长见识了。

本文只是简单模拟下多态,大体上就是C++的虚函数表机制,并没有考虑类域与继承机制,真要讨论起来那就麻烦多了,推荐大家可以看看PY源码解析,里面有简单介绍。

我拿传统的圆与正方形问题为例子,基类是Shape,每个类定义虚函数showShape(),从而体现多态。

额,懒得写了,代码面前了无秘密。。大概思想就是每个结构体头都一样(当作某个基类),这样可以用结构体头指针指向任何结构体,虚函数就是在这个结构体头上做文章,有点绕口了,看代码吧,我把注释写得很详细~

  1. #include <malloc.h> 
  2.  
  3. //定义2个类型意思一下 
  4. enum ShapeType {CIRCLE, SQUARE}; 
  5.  
  6. //虚函数表里的两个函数,calculate也是意思一下,无意义 
  7. typedef void (*show)(); 
  8. typedef double (*calculate)(int arg); 
  9.  
  10. //虚函数表结构体 
  11. typedef struct _VirtualFun 
  12.     show      showShape;  
  13.     calculate calArea; 
  14. } VirtualFun,*pVirtualFun; 
  15.  
  16. //基类,Shape 
  17. typedef struct _Shape 
  18.     ShapeType type; 
  19.     VirtualFun *pfun; 
  20. }Shape,*ShapePointer; 
  21.  
  22. //派生类,Circle 
  23. typedef struct _Circle 
  24.     Shape itsType; 
  25.     int r; 
  26. }Circle; 
  27.  
  28. //派生类,Square 
  29. typedef struct _Square 
  30.     Shape itsType; 
  31.     int d; 
  32. }Square; 
  33.  
  34. //重写的虚函数 
  35. void showCircle() 
  36.     printf("I'm circle/n"); 
  37.  
  38. //重写的虚函数 
  39. void showSquare() 
  40.     printf("I'm square/n"); 
  41.  
  42. //circle初始化 
  43. Circle circle ={ 
  44.     CIRCLE, 
  45.     (pVirtualFun)malloc(sizeof(VirtualFun)), 
  46.     0 
  47. }; 
  48.  
  49. //square初始化 
  50. Square square ={ 
  51.     SQUARE, 
  52.     (pVirtualFun)malloc(sizeof(VirtualFun)), 
  53.     0 
  54. }; 
  55.  
  56.  
  57. //测验多态,只需要传递基类指针ShapePointer。 
  58. void virtualShow(ShapePointer sp) 
  59.     sp->pfun->showShape(); 
  60.  
  61. void main() 
  62.     //虚函数初始化 
  63.     circle.itsType.pfun->showShape = showCircle; 
  64.     square.itsType.pfun->showShape = showSquare; 
  65.      
  66.     //用基类指针指向派生类 
  67.     ShapePointer spc = (ShapePointer)&circle; 
  68.     ShapePointer sps = (ShapePointer)&square; 
  69.      
  70.     //传递基类指针,体现多态。 
  71.     virtualShow(spc); 
  72.     virtualShow(sps); 
  73.     getchar(); 

输出:

I'm circle
I'm square

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值