C++ CSimpleList implementation and test examples

  • 2020-04-02 02:47:43
  • OfStack

This article illustrates the implementation of C++ simple list class. Share with you for your reference. Specific methods are as follows:

The file _afxtls.cpp is as follows:


//#include "StdAfx.h 
#include <stddef.h> 
#include <stdio.h> 
#include "_AFXTLS_.H" 
 
struct MyThreadData{ 
  MyThreadData* pNext; 
  int nShortData; 
}; 
 
void CSimpleList::AddHead(void *p) 
{ 
  *GetNextPtr(p)=m_pHead; 
  m_pHead = p; 
} 
 
BOOL CSimpleList::Remove(void* p) 
{ 
  BOOL bRet = 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; 
    } 
  } 
  return bRet; 
 
} 
 
void main() 
{ 
  MyThreadData* pData; 
  CSimpleList list; 
  list.Construct(offsetof(MyThreadData, pNext)); 
  for (int i=0;i<10;i++) 
  { 
    pData = new MyThreadData; 
    pData->nShortData = i; 
    list.AddHead(pData); 
  } 
 
  //Loop through the linked list, freeing up space occupied by the MyThreadData object
  pData = (MyThreadData*)list.GetHead(); 
  while(pData != NULL) 
  { 
    MyThreadData* pNextData = pData->pNext; 
    printf("The value is %dn",pData->nShortData); 
    delete pData; 
    pData = pNextData; 
  } 
} 

_afxtls.h file is as follows:


//#include "StdAfx.h 
#ifndef __AFXTLS_H__ 
#define __AFXTLS_H__ 
#include <Windows.h> 
class CSimpleList 
{ 
public: 
  CSimpleList(int nNextOffset=0); 
  void Construct(int nNextOffset); 
  //interface
  BOOL IsEmpty() const; 
  void AddHead(void *p); 
  void RemoveAll(); 
  void* GetHead() const; 
  void* GetNext(void* preElement) const; 
  BOOL Remove(void* p); 
 
  //The members required to implement the interface
  void  *m_pHead; 
  size_t m_nextOffset; 
  void** GetNextPtr(void* preElement) const; 
}; 
 
//An inline function of a class
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); 
} 
 
 
#endif

Hope that the article described in the C++ programming to help you.


Related articles: