1.1 完成 Array 类的具体实现
- 数组类创建的原因是: 线性表中重载了数组操作符,容易被误用成数组。
1.1.1
1.1.2 需求分析
- 创建数组类代替原生数组的使用
- 数组类包括长度信息
- 数组类能主动发现越界访问
1.1.3 Array 设计要点
- 抽象类模板,存储空间的位置和大小由子类完成
- 重载数组操作符,判断访问下标是否合法
- 提供数组长度的抽象访问函数
- 提供数组对象间的复制操作
1.1.4 Array 类的声明
template <typename T>
class Array : public Object
{
protected:
T* m_array;
public:
virtual bool set(int i, const T& e);
virtual bool get(int i, T& e) const;
T& operator[](int i);
T operator [](int i) const;
virtual int length() const =0;
};
1.2 完成 StaticArray 类的具体实现
1.2.1 StaticArray 设计要点
- 类模板
- 封装原生数组
- 使用模板参数决定数组的大小
- 实现函数返回数组长度
- copy构造和赋值操作
1.2.2 StaticArray 类的声明
template <typename T, int N>
class StaticArray : public Array<T>
{
protected:
T m_space[N];
public:
StaticArray() //o(1)
//copy构造
StaticArray(const StaticArray<T,N>& obj) // o(n)
//赋值操作
StaticArray& operator = (const StaticArray<T,N>& obj) // o(n)
int length() const // o(1)
};
1.3完成 DynamicArray 类的具体实现
1.3.1DynamicArray 设计要点
- 类模板
- 动态确定内部数组空间的大小
- 实现函数返回数组长度
- copy构造和赋值操作
1.3.2
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 < this->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* tmp = this->m_array;
this->m_array = array;
this->m_length = obj.m_length;
delete[] tmp;
}
else
{
THROW_EXCEPTION(NoEnoughMemoryException, "no memory to create copy object...");
}
}
return *this;
}
int length() const
{
return m_length;
}
void resize(int length)
{
if(this->m_length != length)
{
T* array = new T[length];
if(array != NULL)
{
int size = (this->m_length < length ? this->m_length : length);
for(int i =0; i < size; i++)
{
array[i] = this->m_array[i];
}
T* tmp = this->m_array;
this->m_array = array;
this->m_length =length;
delete[] tmp;
}
else
{
THROW_EXCEPTION(NoEnoughMemoryException,"no enough memory to resize ....");
}
}
}
~DynamicArray()
{
delete[] this->m_array;
}
};
1.3.3 优化
- 重复代码逻辑的抽象
-
init
- 对象构造时的初始化操作
-
copy
- 在堆空间申请新的内存,并执行copy操作
-
update
- 将指定的堆空间作为内部存储数组使用
-
参考一 : 狄泰软件课程
如有侵权:请联系邮箱 1986005934@qq.com