69,369
社区成员
发帖
与我相关
我的任务
分享
#include <stdio.h>
typedef struct
{
void (*draw)(void*);
void (*rotate)(void*);
}ShapeOper;
typedef struct
{
ShapeOper *oper; //虚表指针
}Shape;
typedef struct
{
ShapeOper *oper;
int x,y,w,h;
}Rect;
typedef struct
{
ShapeOper *oper;
int x,y,r;
}Cycle;
void DrawRect( void *p )
{
Rect *me = (Rect *)p;
//............
printf( "DrawRect\n" );
}
void RotateRect( void *p )
{
Rect *me = (Rect *)p;
//............
printf( "RotateRect\n" );
}
void DrawCycle( void *p )
{
Cycle *me = (Cycle *)p;
//............
printf( "DrawCycle\n" );
}
void RotateCycle( void *p )
{
Cycle *me = (Cycle *)p;
//............
printf( "RotateCycle\n" );
}
ShapeOper RectOpers = { &DrawRect, &RotateRect }; //虚函数表
ShapeOper CycleOpers = { &DrawCycle, &RotateCycle };
int main()
{
Rect rt1 = { &RectOpers, 0, 0, 10, 10 };
Cycle cy1 = { &CycleOpers, 10, 10, 20 };
Shape *sh = (Shape *)&rt1;
sh->oper->draw(sh);
sh->oper->rotate(sh);
sh = (Shape *)&cy1;
sh->oper->draw(sh);
sh->oper->rotate(sh);
return 0;
}