课程目标 — 完成顺序存储结构线性表的抽象实现
SeqList 设计要点 — 抽象类模板,存储空间的位置和大小由子类完成 — 实现顺序存储结构线性表的关键操作(增、删、查…) — 提供数组操作符,方便快速获取元素
SeqList.h
#ifndef SEQLIST_H #define SEQLIST_H #include "Exception.h" #include "List.h" namespace DTLib { template <typename T> class SeqList : public List<T> { protected: T* m_array; int m_length; public: bool insert(int i, const T& e) { bool ret = (0 <= i && i <= m_length); ret = (ret && m_length < capacity()); if(ret) { for(int p = m_length-1; p >= i; p--) { m_array[p + 1] = m_array[p]; } m_array[i] = e; m_length++; } return ret; } bool remove(int i) { bool ret = (0 <= i && i < m_length); if(ret) { for(int p = i; p < m_length-1; p++) { m_array[p] = m_array[p + 1]; } m_length--; } return ret; } bool set(int i, const T& e) { bool ret = (0 <= i && i < m_length); if(ret) { m_array[i] = e; } return ret; } bool get(int i, T& e)const { bool ret = (0 <= i && i < m_length); if(ret) { e = m_array[i]; } return ret; } int length()const { return m_length; } void clear() { m_length = 0; } T& operator[](int i) { if(i >=0 && i < m_length) { return m_array[i]; } else { THROW_EXCEPTION(IndexOutOfBoundsException, "Parameter i is Invalid"); } } T operator[](int i)const { return (const_cast<SeqList<T>&>(*this))[i]; //这条语句的意思是把只读对象的只读属性去掉,对象后面加[i]意思就是调用.operator[](i),意思就是调用上一个[]重载函数。 } virtual int capacity()const = 0; }; } #endif // SEQLIST_H思考: