标签:
#include <stdio.h> #include <stdlib.h> /* * * 1. 简单实现模拟虚函数表实现c语言面向对象的设计 * 2. 为实现: 函数注册调用 * 3. 通过文件实现函数注册调用 */ //封装 typedef struct _Shape Shape; //模拟虚函数表 struct ShapeClass { void (*construct)(Shape* self); //构造函数 void (*destroy)(Shape* self); //析构函数 void (*draw)(Shape* self); //处理函数 }; struct _Shape { struct ShapeClass *kclass; int x,y; }; //构造函数 void Shape_construct(Shape* self) {q self->x = 0; self->y = 0; printf("Shape construct\n"); } //析构函数 void Shape_destroy(Shape* self) { printf("shape destroy\n"); //to-do destroy self } void Shape_draw(Shape* self) { printf("draw:%d,%d\n",self->x,self->y); //to-do draw self } //声明_shape_class, 即注册虚函数表 struct ShapeClass _shape_class= { Shape_construct, //函数名就是函数的地址 Shape_destroy, Shape_draw, }; Shape* newShape() { Shape* s = (Shape*)malloc(sizeof(Shape)); s->kclass = &_shape_class; s->kclass->construct(s); return s; } void deleteShape(Shape* shape) { shape->kclass->destroy(shape); free(shape); } int main() { Shape* shape = newShape(); shape->kclass->draw(shape); deleteShape(shape); }
标签:
原文地址:http://my.oschina.net/u/573270/blog/413479