自定义一个动态数组

2014-11-23 23:13:36 · 作者: · 浏览: 0

/******************************动态数组****************************************/
#include 
  
   
#include 
   
     typedef unsigned char BYTE; template
    
      class carray { public: carray():m_nSize(0),pdata(NULL){} ~carray(); void add(Type newElement); int getsize(); Type operator[](int nIndex) const; Type& operator[](int nIndex); private: int m_nSize; Type* pdata; }; template
     
       carray
      
       ::~carray() { if (pdata != NULL) { // for (;m_nSize--;pdata++) // pdata->~Type(); delete[] (BYTE*)pdata; } } /********************************************************************************/ /* 以下添加元素这个部分很重要 */ /********************************************************************************/ template
       
         void carray
        
         ::add(Type newElement) { if (pdata == NULL) { pdata = (Type*) new BYTE[sizeof(Type)]; memset((void*)pdata,0,sizeof(Type)); ::new((void*)pdata) Type; } else { Type* pNewData = (Type*) new BYTE[(m_nSize+1) * sizeof(Type)]; memcpy(pNewData,pdata,m_nSize*sizeof(Type)); memset((void*)&pNewData[m_nSize],0,sizeof(Type)); ::new((void*)&pNewData[m_nSize]) Type; delete[] (BYTE*)pdata; pdata = pNewData; } pdata[m_nSize++] = newElement; } template
         
int carray ::getsize() { return m_nSize; } template Type carray ::operator [](int nIndex) const { return pdata[nIndex]; } template Type& carray ::operator [](int nIndex) { return pdata[nIndex]; } /*************************************************************************************/