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

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

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

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

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

 

#include <malloc.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

 

你可能感兴趣的:(娱乐,C语言模拟C++虚函数多态性。)