c语言实现虚函数表

wwwhhb4001 2009-02-25 10:25:06

请教高手,c语言实现虚函数表,实现c++的多态,该怎么做?

明天我再加100分

...全文
612 11 打赏 收藏 转发到动态 举报
写回复
用AI写文章
11 条回复
切换为时间正序
请发表友善的回复…
发表回复
  • 打赏
  • 举报
回复
http://www.crazycoder.cn/Tag/19620/Index.html
thesecretblue 2009-02-26
  • 打赏
  • 举报
回复
up!!!
dongpy 2009-02-26
  • 打赏
  • 举报
回复
一个简单例子,用函数指针实现多态。
#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;
}
dongpy 2009-02-26
  • 打赏
  • 举报
回复
虚函数表实现容易,但要做到真正面向对象就难了,抽象继承多态,等于做CPP编译器的工作。
Dinelgua 2009-02-26
  • 打赏
  • 举报
回复
楼主照 深入探索 c++对象模型 提供的三种方式任选其一就可以实现
dongpy 2009-02-26
  • 打赏
  • 举报
回复
楼主是要用C写一个实用的面向对象框架,or只是学习一下思路?
lingyin55 2009-02-26
  • 打赏
  • 举报
回复
mark 复杂的话直接用c++算了,毕竟那是人家做好的东西。
xtting_8984313 2009-02-26
  • 打赏
  • 举报
回复
不知道lz知道“object c”吗,仿佛是lz想要的,是一个c的面向对象库。
基本意思就是用c实现面向对象的一些内容,我不是很了解,不知道是否能满足要求。
xtting_8984313 2009-02-26
  • 打赏
  • 举报
回复
lz的意思是到什么程度啊。
感觉简单点的函数指针就可以了,做一个函数指针数组,然后根据偏移量调用。不过如果涉及到函数参数不一致的情况就会麻烦一些了,感觉会很乱。
ltc_mouse 2009-02-25
  • 打赏
  • 举报
回复
没必要做编译器做的事情吧~

简单的,函数指针就可以了;复杂的,直接用C++吧
waizqfor 2009-02-25
  • 打赏
  • 举报
回复
[Quote=引用楼主 wwwhhb4001 的帖子:]

请教高手,c语言实现虚函数表,实现c++的多态,该怎么做?

明天我再加100分
[/Quote]
http://topic.csdn.net/t/20060823/16/4970301.htmlLZ看看这个帖子 能很有收获

69,369

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧