您的位置:首页 > 编程语言 > C语言/C++

自定义一个动态数组

2014-04-16 23:13 381 查看
/******************************动态数组****************************************/
#include <memory>
#include <new>
typedef unsigned char BYTE;
template<class Type>
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<class Type>
carray<Type>::~carray()
{
if (pdata != NULL)
{
// for (;m_nSize--;pdata++)
// pdata->~Type();
delete[] (BYTE*)pdata;
}
}

/********************************************************************************/
/* 以下添加元素这个部分很重要 */
/********************************************************************************/
template<class Type>
void carray<Type>::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<class Type>
int carray<Type>::getsize()
{
return m_nSize;
}

template<class Type>
Type carray<Type>::operator [](int nIndex) const
{
return pdata[nIndex];
}

template<class Type>
Type& carray<Type>::operator [](int nIndex)
{
return pdata[nIndex];
}
/*************************************************************************************/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  c++ 技术 对象
相关文章推荐