需求分析
-创建数组类代替原生数组的使用
·数组类包含长度信息
·数组类能够主动发现越界访问
Array设计要点
-抽象类模板,存储空间的位置和大小由子类完成
-重载数组操作符,判断访问下标是否合法
-提供数组长度的抽象访问函数
-提供数组对象间的复制操作
Array类的声明
template <typename T>
class Array : public Object
{
protected:
T* m_array;
public:
virtual bool set(int i,const T& e)
{
bool ret = ((0 <= i) && (i < length()));
if(ret)
{
m_array[i] = e;
}
return ret;
}
virtual bool get(int i,T& e) const
{
bool ret = ((0 <= i) && (i < length()));
if(ret)
{
e = m_array[i];
}
return ret;
}
T& operator[] (int i)
{
if((0 <= i) && (i < length()))
{
return m_array[i];
}
else
{
//抛出异常
}
}
T operator[] (int i) const
{
return (const_cast<Array<T>&>(*this)[i]);
}
virtual int length() const = 0;
};
StaticArray设计要点
-类模板
·封装原生数组
·使用模板参数决定数组大小
·实现函数返回数组长度
·拷贝构造和赋值操作
StaticArray类的声明
template <typename T, int N>
class StaticArray : public Array<T>
{
protected:
T m_space[N];
public:
StaticArray()
{
this->m_array = m_space;
}
StaticArray(const StaticArray<T,N>& obj)
{
this->m_array = m_space;
for(int i = 0; i<N ;i++)
{
m_space[i] = obj.m_space[i];
}
}
StaticArray<T,N>& operator= (const StaticArray<T,N>& obj)
{
if(this != &obj)
{
for(int i =0;i<N ;i++)
{
m_space[i] = obj.m_space[i];
}
}
return *this;
}
int length() const
{
return N;
}
};
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;
}
else
{
//抛出异常
}
}
void init(T* array,int length)
{
if(array != NULL)
{
this->m_array = array;
this->m_length = length;
}
else
{
//抛出异常
}
}
public:
DynamicArray(int length)
{
init(new T[length],length);
}
DynamicArray(const DynamicArray<T>& obj)
{
init(copy(obj.m_array,obj.m_length,obj,m_length,obj.m_length),obj.m_length);
}
DynamicArray<T>& operator= (const DynamicArray<T>& obj)
{
if(this != &obj)
{
update(copy(obj.m_array,obj.m_length,obj.m_length),obj.m_length);
}
return *this;
}
void resize(int length)
{
if(length != m_length)
{
update(copy(this->m_array,m_length,length),length);
}
}
int length() const
{
return m_length;
}
~DynamicArray()
{
}
};
总结:
-StaticArray通过封装原生数组的方式实现数组类
-DynamicArray动态申请堆空间,是的数组长度动态可变
-数组对象能够代替原生数组,并且使用上更安全
-代码优化是项目开发过程中不可或缺的环节