C++中CSimpleList的实现与测试实例
本文实例讲述了C++简单列表类的实现方法。分享给大家供大家参考。具体方法如下:
_AFXTLS.CPP文件如下:
//#include"StdAfx.h #include<stddef.h> #include<stdio.h> #include"_AFXTLS_.H" structMyThreadData{ MyThreadData*pNext; intnShortData; }; voidCSimpleList::AddHead(void*p) { *GetNextPtr(p)=m_pHead; m_pHead=p; } BOOLCSimpleList::Remove(void*p) { BOOLbRet=FALSE; if(p==NULL) { bRet=FALSE; } if(p==m_pHead) { m_pHead=GetNext(m_pHead); bRet=TRUE; } else { void*pTest; pTest=m_pHead; while(pTest&&(GetNext(pTest)!=p)) { pTest=GetNext(pTest); } if(pTest!=NULL) { *GetNextPtr(pTest)=GetNext(p); bRet=TRUE; } } returnbRet; } voidmain() { MyThreadData*pData; CSimpleListlist; list.Construct(offsetof(MyThreadData,pNext)); for(inti=0;i<10;i++) { pData=newMyThreadData; pData->nShortData=i; list.AddHead(pData); } //遍历链表,释放MyThreadData对象占用的空间 pData=(MyThreadData*)list.GetHead(); while(pData!=NULL) { MyThreadData*pNextData=pData->pNext; printf("Thevalueis%d\n",pData->nShortData); deletepData; pData=pNextData; } }
_AFXTLS_.H文件如下:
//#include"StdAfx.h #ifndef__AFXTLS_H__ #define__AFXTLS_H__ #include<Windows.h> classCSimpleList { public: CSimpleList(intnNextOffset=0); voidConstruct(intnNextOffset); //接口 BOOLIsEmpty()const; voidAddHead(void*p); voidRemoveAll(); void*GetHead()const; void*GetNext(void*preElement)const; BOOLRemove(void*p); //为实现接口所需的成员 void*m_pHead; size_tm_nextOffset; void**GetNextPtr(void*preElement)const; }; //类的内联函数 inlineCSimpleList::CSimpleList(intnNextOffset) {m_pHead=NULL;m_nextOffset=nNextOffset;} inlinevoidCSimpleList::Construct(intnNextOffset) {m_nextOffset=nNextOffset;} inlineBOOLCSimpleList::IsEmpty()const { returnm_pHead==NULL; } //inlinevoidAddHead(void*p) //{ // //} inlinevoidCSimpleList::RemoveAll() { m_pHead=NULL; } inlinevoid*CSimpleList::GetHead()const { returnm_pHead; } inlinevoid*CSimpleList::GetNext(void*preElement)const { return*GetNextPtr(preElement); } //inlineBOOLCSimpleList::Remove(void*p) //{ // //} inlinevoid**CSimpleList::GetNextPtr(void*preElement)const { return(void**)((BYTE*)preElement+m_nextOffset); } #endif
希望本文所述对大家的C++程序设计有所帮助。