#pragma once//函數文件 #include<iostream> #include<string> #include<assert.h> using namespace std; template<class DataType > class SeqList { private: DataType* _data; size_t _capacity; size_t _size; void ChickCapacity(); public: SeqList(); SeqList(const DataType& data); SeqList(const SeqList& tmp); ~SeqList(); void PushBack(const DataType& data); void PopBack(); void operator=(const SeqList& tmp); void Display(); }; template<class DataType> SeqList<DataType>::SeqList() :_data(NULL) , _size(0) , _capacity(0) {} template<class DataType> SeqList<DataType>::SeqList(const DataType& data) :_data(NULL) , _size(0) , _capacity(0) { PushBack(data); } template<class DataType> void SeqList< DataType>::ChickCapacity() { if (_capacity == 0) { _capacity = 1; _data = new DataType[_capacity]; } if (_size == _capacity) { _capacity *= 2; DataType* tmp = new DataType[_capacity]; size_t index = 0; while (index < _size) { tmp[index] = _data[index]; ++index; } delete[] _data; _data = tmp; } } template<class DataType> SeqList<DataType>::SeqList(const SeqList& tmp) :_size(tmp._size) , _capacity(tmp._capacity) , _data( new DataType[_size]) { size_t index = 0; while (index < _size) { _data[index] = tmp._data[index]; ++index; } } template<class DataType> SeqList<DataType>::~SeqList() { delete[] _data; } template<class DataType> void SeqList<DataType>::PushBack(const DataType& data) { ChickCapacity(); _data[_size++] = data; } template<class DataType> void SeqList<DataType>::PopBack() { if (_size > 0) --_size; if (_size == 0 && _data != NULL) { delete[] _data; _data = NULL; } } template<class DataType> void SeqList<DataType>::operator=(const SeqList& tmp) { if (&tmp == this) return; _size = tmp._size; _capacity = tmp._capacity; delete[] _data; _data = new DataType[_capacity]; size_t index = 0; while (index < _size) { _data[index] =tmp._data[index] ; ++index; } } template<class DataType> void SeqList<DataType>::Display() { size_t index = 0; while (index < _size) { cout << _data[index] << "--" << endl; ++index; } } #include<iostream>//主函數 #include<string> #include"seqlist.h" using namespace std; void test1() { //SeqList<int> s1; //s1.PushBack(1); //s1.PushBack(2); //s1.PushBack(3); //s1.PushBack(4); //s1.Display(); //s1.PopBack(); //s1.PopBack(); //s1.PopBack(); //s1.PopBack(); //s1.PopBack(); //s1.Display(); SeqList<string> s2("我是帥哥!0"); s2.PushBack("我是帥哥!1"); s2.PushBack("我是帥哥!2"); s2.PushBack("我是帥哥!3"); s2.PushBack("我是帥哥!4"); s2.Display(); SeqList<string> s1; s1 = s2; s1.Display(); s2.PopBack(); s2.PopBack(); s2.PopBack(); s2.PopBack(); s2.PopBack(); s2.PopBack(); s2.Display(); } int main() { test1(); return 0; }