C语言模拟C++的多态性

#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)□
	
	//传递基类指针,体现多态。
	virtualShow(spc);
	virtualShow(sps);
	getchar();
}
http://blog.csdn.net/shallwake/article/details/4943365
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值