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