C++模板类的用法实例
本文实例讲述了C++中模板类的用法,分享给大家供大家参考。具体方法如下:
//#include "StdAfx.h #ifndef __AFXTLS_H__ #define __AFXTLS_H__ #include <Windows.h> class CSimpleList { public: CSimpleList(int nNextOffset=0); void Construct(int nNextOffset); //接口 BOOL IsEmpty() const; void AddHead(void *p); void RemoveAll(); void* GetHead() const; void* GetNext(void* preElement) const; BOOL Remove(void* p); //为实现接口所需的成员 void *m_pHead; size_t m_nextOffset; void** GetNextPtr(void* preElement) const; }; //类的内联函数 inline CSimpleList::CSimpleList(int nNextOffset) {m_pHead = NULL; m_nextOffset = nNextOffset; } inline void CSimpleList::Construct(int nNextOffset) {m_nextOffset = nNextOffset; } inline BOOL CSimpleList::IsEmpty() const { return m_pHead==NULL; } //inline void AddHead(void *p) //{ // //} inline void CSimpleList::RemoveAll() { m_pHead = NULL; } inline void* CSimpleList::GetHead() const { return m_pHead; } inline void* CSimpleList::GetNext(void* preElement) const { return *GetNextPtr(preElement); } //inline BOOL CSimpleList::Remove(void* p) //{ // //} inline void** CSimpleList::GetNextPtr(void* preElement) const { return (void**)((BYTE*)preElement+m_nextOffset); } //定义模板类 template<class TYPE> class CTypedSimpleList:public CSimpleList { public: CTypedSimpleList(int nNextOffset=0) :CSimpleList(nNextOffset){} void Construct(int nNextOffset); //接口 void AddHead(TYPE p) { CSimpleList::AddHead((void*)p); } TYPE GetHead() { return (TYPE)CSimpleList::GetHead(); } TYPE GetNext(TYPE preElement) { return (TYPE)CSimpleList::GetNext((void*)preElement); } BOOL Remove(TYPE p) { return CSimpleList::Remove(p); } //直接引用类的对象会调用此函数 operator TYPE() { return (TYPE)CSimpleList::GetHead(); } }; #endif
模板类的用法:
//测试模板类 MyThreadData* pTempData; CTypedSimpleList<MyThreadData*> templateList; list.Construct(offsetof(MyThreadData, pNext)); //向链表中加数据 for (int i=100;i<110;i++) { pTempData = new MyThreadData; pTempData->nShortData = i; templateList.AddHead(pTempData); } //遍历链表,释放对象占用的资源 pTempData = templateList; while (pTempData) { MyThreadData* pNextTempData = pTempData->pNext; printf("TemplateDateList=%d\n",pTempData->nShortData); delete pTempData; pTempData = pNextTempData; }
希望本文所述对大家的C++程序设计有所帮助。
赞 (0)