面向对象的C语言框架尝鲜

从学习编程开始就一直被灌输面向对象,继承,多态等等思想,工作后遇到一些纯C的编程工作还是有些不习惯,毕竟用C实现库以及中间件给别人使用也还是不如C++方便直观。

这几天偶然看到一个轻量级的面向对象的C编程框架LW_OOPC,作者通过宏定义封装了面向对象编程的一些工具,我们可以用来方便的指定类,继承,借口等。

首先下载框架包含到我们的项目中来(lw_oopc.h以及lw_oopc.c两个文件),我下面首先定义一个抽象类People,和一个Friend类,以及一个接口放在friend.h头文件中

#ifndef __FRIEND_H
#define __FRIEND_H

/*
 *  friend.h
 */

#include "lw_oopc.h"

INTERFACE(ICall)
{
	void (*call)(ICall *ic);
};

ABS_CLASS(People)
{
	char name[100];
	int  age;
	
	void (*say)(People* p,const char *word);
	void (*init)(People* p,const char* name,int age);
};

CLASS(Friend)
{
	EXTENDS(People);
	IMPLEMENTS(ICall);
	
	int tel;
	
	void (*init)(Friend* f,const char* name,int age,int tel);
};

#endif

类的声明很简单,主要是用框架中定义的几个宏替代C++中类的声明语法,接下来是类的成员函数的定义放在friend.c源文件中

/*
 *  friend.c
 */

#include "friend.h"

void People_Say(People* p,const char* word)
{
	printf("%s¥n",word);
}

void People_Init(People* p,const char* name,int age)
{
	strcpy(p->name,name);
	p->age = age;
}

ABS_CTOR(People)
FUNCTION_SETTING(say,People_Say);
FUNCTION_SETTING(init,People_Init);
END_ABS_CTOR

void Friend_Init(Friend* f,const char *name,int age,int tel)
{
	People *p = SUPER_PTR(f,People);
	People_Init(p,name,age);
	f->tel = tel;
}

void Friend_Call(Friend* f)
{
	printf("Hello Friend");
}

CTOR(Friend)
SUPER_CTOR(People);
FUNCTION_SETTING(init,Friend_Init);
FUNCTION_SETTING(ICall.call,Friend_Call);
END_CTOR

最后是我们的测试main.c

#include <stdio.h>
#include "lw_oopc.h"
#include "friend.h"


int main (int argc, const char * argv[]) {
    // insert code here...
    
	Friend* f = Friend_new();
	f->init(f,"penjin",25,1590000000);
	
	People* p = SUPER_PTR(f,People);
	printf("Friend'name is %s and age is %d and tel number is %d¥n",p->name,p->age,f->tel);
	
	ICall* ic = SUPER_PTR(f,ICall);
	ic->call(f);
	
	lw_oopc_delete(f);
	
	lw_oopc_report();
    return 0;
}
输出结果Friend'name is penjin and age is 25 and tel number is 1590000000 ¥n Hello Friend

使用起来还算比较方便简单的,将来如果遇到想实现C的面向对象编程,这个框架是个不错的选择,呵呵

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值