c语言来实现c++
时间:2014-05-08 16:14:30
收藏:0
阅读:363
闲来没事,看了看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;
}
评论(0)