首页 > 学院 > 开发设计 > 正文

在C语言中引入类的概念

2019-11-17 05:15:41
字体:
来源:转载
供稿:网友

基于对象的程序设计的好处大家应该都有一定的体会,但是在 C 语言中并不支持类的概念,不过我们可以通过 strUCt 实现一些基础的类对象,如队列、堆栈等。通过对象的实现可以在一定程度上提高编程效率、简化 C程序设计。下面使用一个例子来介绍下如何在实现一个简单的类,希望对大家有些益处:

/* 应用消息队列类 */
struct AppQueue{
struct AppFrame *pHead, *pTail;

void (*InQueue)(struct AppQueue *papq, struct AppFrame *apf);
struct AppFrame * (*OutQueue)(struct AppQueue *papq);
unsigned char (*Empty)(struct AppQueue *papq);
void (*ClearQueue)(struct AppQueue *papq);
};

/* AppQueue 类成员函数实体 */
void apq_InQueue(struct AppQueue *papq, struct AppFrame *apf)
{
if(apf == NULL) return;

apf->pNext = NULL;

if(papq->pTail != NULL){
papq->pTail->pNext = apf;
papq->pTail = apf;
}
else{
papq->pHead = papq->pTail = apf;
}

}

struct AppFrame * apq_OutQueue(struct AppQueue *papq)
{
struct AppFrame *paf;

paf = papq->pHead;

if(papq->pHead != papq->pTail){
papq->pHead = papq->pNext;
}
else{
papq->pHead = papq->pTail = NULL;
}

return paf;
}

unsigned char apq_Empty(struct AppQueue *papq)
{
if((papq->pHead == papq->pTail) && (papq->pTail == NULL))
return TRUE;
else
return FALSE;
}

void apq_ClearQueue(struct AppQueue *papq)
{
struct AppFrame *paf;
while((paf = papq->OutQueue(papq)) != NULL){
SysAppPool.Free(&SysAppPool, paf);
}
}

/* AppQueue 类对象初始化 */
void InitAppQueue(struct AppQueue *papq)
{
papq->pHead = papq->pTail = NULL;

papq->InQueue = apq_InQueue;
papq->OutQueue = apq_OutQueue;
papq->Empty = apq_Empty;
papq->ClearQueue = apq_ClearQueue;
}

Qiyaismine@163.com

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表