c语言来实现c++

来源:互联网 发布:印度阅兵知乎 编辑:程序博客网 时间:2024/05/03 11:57

闲来没事,看了看sqlite的源码,突然想用c实现c++,写了如下demo,自我感觉不错

#include <stdio.h>#include <stdlib.h>struct Class;typedef struct Class _Class;struct IMethod{void (*ctor)(_Class *c);void (*dtor)(_Class *c);int (*sum)(_Class* c);int (*getValueA)(_Class* c);int (*getValueB)(_Class* c);void (*setValueA)(_Class*c, int a);void (*setValueB)(_Class *c, int b);};typedef struct IMethod _IMethod;typedef struct Class{//数据int m_a;int m_b;//接口_IMethod m_method;} _Class;int _sum(_Class *c){return c->m_a+c->m_b;}int _getValueA(_Class *c){return c->m_a;}int _getValueB(_Class *c){return c->m_b;}void _setValueA(_Class *c, int a){c->m_a = a;}void _setValueB(_Class *c, int b){c->m_b = b;}void _ctor(_Class *c){printf("create new _Class\n");//初始化数据,构造函数c->m_method.sum = &_sum;c->m_method.getValueA = &_getValueA;c->m_method.getValueB = &_getValueB;c->m_method.setValueA = &_setValueA;c->m_method.setValueB = &_setValueB;c->m_a = 0;c->m_b = 0;}void _dtor(_Class *c){printf("delete _Class\n");//析构函数}//_Class的对象工厂_Class *newClass(){_Class* obj= (_Class*)malloc(sizeof(_Class));_ctor(obj);return obj;}void deleteClass(_Class * c){_dtor(c);free(c);}#define CXX_CALLER(obj, fun,...)\obj->m_method.fun(obj, __VA_ARGS__);\int main(int argc, char *argv[]){_Class *c = newClass();int a=0, b=0, sum=0;CXX_CALLER(c, setValueA, 100);CXX_CALLER(c, setValueB, 200);// c->m_method.setValueA(100);// c->m_method.setValueB(200);// a = c->m_method.getValueA(c);// b = c->m_method.getValueB(c);// sum = c->m_method.sum(c);a = CXX_CALLER(c, getValueA);b = CXX_CALLER(c, getValueB);sum = CXX_CALLER(c, sum);printf("a=%d, b=%d, sum=%d\n", a, b, sum);deleteClass(c);getchar();return 0;}


4 0
原创粉丝点击