在C語言中引入類的概念(轉)

post0發表於2007-08-11
在C語言中引入類的概念(轉)[@more@]

基於物件的程式設計的好處大家應該都有一定的體會,但是在 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.co

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/8225414/viewspace-944603/,如需轉載,請註明出處,否則將追究法律責任。

相關文章