C++模板类的用法实例
本文实例讲述了C++中模板类的用法,分享给大家供大家参考。具体方法如下:
//#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); } //定义模板类 template<classTYPE> classCTypedSimpleList:publicCSimpleList { public: CTypedSimpleList(intnNextOffset=0) :CSimpleList(nNextOffset){} voidConstruct(intnNextOffset); //接口 voidAddHead(TYPEp) { CSimpleList::AddHead((void*)p); } TYPEGetHead() { return(TYPE)CSimpleList::GetHead(); } TYPEGetNext(TYPEpreElement) { return(TYPE)CSimpleList::GetNext((void*)preElement); } BOOLRemove(TYPEp) { returnCSimpleList::Remove(p); } //直接引用类的对象会调用此函数 operatorTYPE() { return(TYPE)CSimpleList::GetHead(); } }; #endif
模板类的用法:
//测试模板类 MyThreadData*pTempData; CTypedSimpleList<MyThreadData*>templateList; list.Construct(offsetof(MyThreadData,pNext)); //向链表中加数据 for(inti=100;i<110;i++) { pTempData=newMyThreadData; pTempData->nShortData=i; templateList.AddHead(pTempData); } //遍历链表,释放对象占用的资源 pTempData=templateList; while(pTempData) { MyThreadData*pNextTempData=pTempData->pNext; printf("TemplateDateList=%d\n",pTempData->nShortData); deletepTempData; pTempData=pNextTempData; }
希望本文所述对大家的C++程序设计有所帮助。