数组类的创建(下):DynamicArray
Posted 学习只为旅行
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了数组类的创建(下):DynamicArray相关的知识,希望对你有一定的参考价值。
#ifndef DYNAMICARRAY_H
#define DYNAMICARRAY_H
#include "array.h"
#include "Exception.h"
namespace DragonLib {
template <typename T>
class DynamicArray : public Array<T>
{
protected:
int m_length;
public:
DynamicArray(int length)
{
this->m_array=new T[length];
if(this->m_array!=NULL)
{
this->m_length=length;
}
else
{
THROW_EXCEPTION(NoEnoughMemoryException,"No memory to create DynamicArray object...");
}
}
DynamicArray(const DynamicArray<T>& obj)
{
this->m_array=new T[obj.m_length];
if(this->m_array!=NULL)
{
this->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 memory to create DynamicArray object...");
}
}
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 memory to create copy object...");
}
}
return *this;
}
int length() const
{
return m_length;
}
void resize(int length)
{
if(length != m_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 memory to resize object...");
}
}
}
~DynamicArray()
{
delete[] this->m_array;
}
};
}
#endif // DYNAMICARRAY_H
改写:
小结
以上是关于数组类的创建(下):DynamicArray的主要内容,如果未能解决你的问题,请参考以下文章