DynamicArray
上一篇说到了数组类的一种具体对象,这篇里面来说另一种。就是DynamicArray,既然StaticArray已经够好了,为什么还要有DynamicArray呢。就如同前几片博客里讲的基于顺序存储结构的线性表的两种实现一样,我们想让这个对象可以动态的改变自己的存储空间的大小,这样就会更加灵活。
设计要点:
类模板
在堆中申请一定的空间作为存储空间
实现函数返回长度
拷贝构造和赋值
动态确定内部数组空间
程序表现:
template <typename T>
class DynamicArray : public Array<T>
{
protected:
int m_length;
T* copy(T* array, int len, int newlen);
void update(T* array, int length);
public:
DynamicArray(int length);
DynamicArray(const DynamicArray<T>& obj);
int length() const;
void resize(int length);
DynamicArray<T>& operator = (const DynamicArray<T>& obj);
~DynamicArray();
};
代码实现:
template <typename T>
class DynamicArray : public Array<T>
{
protected:
int m_length;
T* copy(T* array, int len, int newlen)
{
T* ret = new T[newlen];
if(ret != NULL)
{
int size = (len < newlen) ? len : newlen;
for(int i=0; i<size; i++)
{
ret[i] = array[i];
}
}
return ret;
}
void update(T* array, int length)
{
if(array != NULL)
{
T* temp = this->m_array;
this->m_array = array;
this->m_length = length;
delete[] temp;
}
}
public:
DynamicArray(int length)
{
this->m_array = new T[length];
if( this->m_array != NULL)
{
m_length = length;
}
else
{
THROW_EXCEPTION(NoEnoughMemoryException,"No enough memory to creat DynamicArray!");
}
}
DynamicArray(const DynamicArray<T>& obj)
{
this->m_array = new T[obj.m_length];
if( this->m_array != NULL)
{
m_length = obj.m_length;
for(int i=0; i<obj.m_length; i++)
{
this->m_array[i] = obj.m_array[i];
}
}
else
{
THROW_EXCEPTION(NoEnoughMemoryException,"No enough memory to creat DynamicArray!");
}
}
int length() const
{
return m_length;
}
void resize(int length)
{
if(m_length != length)
{
T* array = new T[length];
if( array != NULL)
{
int size = (length < m_length) ? length : m_length;
for(int i=0; i<size; i++)
{
array[i] = this->m_array[i];
}
T* temp = this->m_array;
this->m_array = array;
this->m_length = length;
delete[] temp;
}
else
{
THROW_EXCEPTION(NoEnoughMemoryException,"No enough memory to creat DynamicArray!");
}
}
}
DynamicArray<T>& operator = (const DynamicArray<T>& obj)
{
if(this != &obj)
{
T* array = new T[obj.m_length];
if( array != NULL)
{
for(int i=0; i<obj.m_length; i++)
{
array[i] = obj.m_array[i];
}
T* temp = this->m_array;
this->m_array = array;
this->m_length = obj.m_length;
delete[] temp;
}
else
{
THROW_EXCEPTION(NoEnoughMemoryException,"No enough memory to copy DynamicArray!");
}
}
return *this;
}
~DynamicArray()
{
delete[] this->m_array;
}
};