基于对象的程序设计的好处大家应该都有一定的体会,但是在 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; } |