- 完成 Array 類的具體實現
- 完成 StaticArray 類的具體實現
建立數組類代替原生數組的使用ios
- 數組類包含長度信息
- 數組類可以主動發現越界訪問
- 抽象類模板,存儲空間的位置和大小由子類完成
- 重載數組操做符,判斷訪問下標是否合法
- 提供數組長度的抽象訪問函數
- 提供數組對象間的複製操做
template <typename T> class Array : public Object { public: virtual bool set(int i, const T &e); virtual bool get(int i, T &e) const; virtual int length() const = 0; T &operator[] (int i); T operator[] (int i) const; protected: T *m_array; };
#ifndef ARRAY_H #define ARRAY_H #include "Object.h" #include "Exception.h" namespace DTLib { template <typename T> class Array : public Object { public: virtual bool set(int i, const T &e) // O(1) { bool ret = ((0 <= i) && (i < length())); if (ret) { m_array[i] = e; } return ret; } virtual bool get(int i, T &e) const // O(1) { bool ret = ((0 <= i) && (i < length())); if (ret) { e = m_array[i]; } return ret; } T &operator[] (int i) // O(1) { if ((0 <= i) && (i < length())) { return m_array[i]; } else { THROW_EXCEPTION(IndexOutOfBoundsException, "Paramter i is invalid ..."); } } T operator[] (int i) const // O(1) { return const_cast<Array<T>&>(*this)[i]; } virtual int length() const = 0; protected: T *m_array = nullptr; }; } #endif // ARRAY_H
類模板編程
- 封裝原生數組
- 使用模板參數決定數組大小
- 實現函數返回數組長度
- 拷貝和賦值操做
template <typename T, int N> class StaticArray : public Array<T> { public: StaticArray(); StaticArray(const StaticArray<T, N> &obj); StaticArray<T, N> &operator= (const StaticArray<T, N> &obj); int length() const; protected: T m_space[N]; };
StaticArray.h數組
#ifndef STATICARRAY_H #define STATICARRAY_H #include "Array.h" namespace DTLib { template <typename T, int N> class StaticArray : public Array<T> { public: StaticArray() // O(1) { this->m_array = m_space; } StaticArray(const StaticArray<T, N> &obj) // O(n) { 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) // O(n) { if (this != &obj) { for (int i=0; i<N; ++i) { m_space[i] = obj.m_space[i]; } } return *this; } int length() const // O(1) { return N; } protected: T m_space[N]; }; } #endif // STATICARRAY_H
文件:main.cpp函數
#include <iostream> #include "StaticArray.h" using namespace std; using namespace DTLib; int main() { cout << "main begin" << endl; StaticArray<int, 5> a; for (int i=0; i<a.length(); ++i) { a[i] = i * i; } for (int i=0; i<a.length(); ++i) { cout << a[i] << endl; } cout << "---------" << endl; StaticArray<int, 5> a1; a1 = a; for (int i=0; i<a1.length(); ++i) { cout << a1[i] << endl; } cout << "main end" << endl; return 0; }
輸出:this
main begin 0 1 4 9 16 --------- 0 1 4 9 16 main end
思考:
如歌實現DynamicArray?
DynamicArray 與 StaticArray 的差距在哪裏?spa
以上內容整理於狄泰軟件學院系列課程,請你們保護原創!設計