本文只實現了Vector的默認構造函數、賦值構造函數、賦值函數、析構函數、重置空間大小函數和插入函數,權當起到拋磚引玉的做用,其餘函數功能的實現可在此基礎之上進行拓展。ios
#include <iostream> using namespace std; template <class T> class Vector { public: // 構造函數 Vector(int size=0):theSize(size),theCapacity(size+SPACE_CAPACITY){ data = new T[theCapacity]; } // 複製構造函數 Vector(const Vector& other) :theSize(0),theCapacity(0),data(NULL){ *this=other; } // 重載賦值函數 Vector& operator=(Vector& other) { // 判斷是否爲自身賦值 if (this == &other) return *this; else { delete[]data; theSize = other.theSize; theCapacity = other.theCapacity; data = new T[theCapacity]; for (int i = 0; i < theSize; ++i) { data[i] = other.data[i]; } return *this; } } // 析構函數 ~Vector(void) { delete[] data; } // 從新分配空間大小函數 void reServe(int newCapacity) { if (newCapacity <= theCapacity) return; T *temp = data; data = new T[newCapacity]; for (int i = 0; i < theSize; ++i) data[i] = temp[i]; delete[] temp; } // push_back函數 void push_back(T val) { if (theSize == theCapacity) reServe(2 * theCapacity + 1); data[theSize++] = val; } private: const int SPACE_CAPACITY = 16; int theCapacity; int theSize; T *data; };