闲来没事,看了看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;
}

最新文章

  1. winform窗体弹出时,光标默认显示在指定的输入框内
  2. 动态生成DropDownList 并取值
  3. 安装beautifulsoup4
  4. ios layer 动画-(transform.rotation篇)
  5. Leetcode 231 Power of Two 数论
  6. C++之多态的一个例子
  7. crsctl stat res -t 和 crsctl stat res -init -t
  8. acm算法模板(5)
  9. linux ----虚拟机无法与本地机通信
  10. codeforces 630H (组合数学)
  11. ubuntuy用户切换和密码修改
  12. C语言-06复杂数据类型-04 结构体
  13. css包含块containing block
  14. Chapter 1 Securing Your Server and Network(3):使用托管服务帐号
  15. 编写一个闹钟和定时关机工具(MFC VS2010)
  16. eclipse中集成svn maven开发手册---导入项目
  17. Project Euler:Product-sum numbers (problem 88) C++
  18. Yii的HTML助手
  19. JAVA生成数字0~9字母A~Z混合编码0000、0001...0009、000A...000Z、0010......
  20. 安装Redis 4.0单实例

热门文章

  1. winform基础——实现简易赈灾物资发放登记系统
  2. Lazy Math Instructor
  3. Boost的安装与使用(整整83篇)
  4. Thinkphp入门三—框架模板、变量(47)
  5. Eclipse无提示的解决办法 和 内容辅助技巧
  6. 基于visual Studio2013解决C语言竞赛题之1094纵横图
  7. linux系统日志及其rsyslog服务
  8. Swift - 列表项尾部附件点击响应(感叹号,箭头等)
  9. 测试关闭mojo utf-8
  10. HDU 4707 Pet(DFS(深度优先搜索)+BFS(广度优先搜索))