main.cpp #include<iostream> #include<string> #include"Stack.hpp" using namespace std; void test1(){ //測試 Stack<int> s1; s1.Push(1); s1.Push(2); s1.Push(3); s1.Push(4); s1.Pop(); s1.Pop(); s1.Pop(); s1.Pop(); } int main(){ test1(); return 0; } Stack.hpp #pragma once template <class T> //使用模板可以實現多種類型棧操作 class Stack{ private: T* _array; //數據結構 size_t _capacity; //入棧個數 int _topindex; //棧空/滿的判斷標准 public: Stack() :_array(0) , _capacity(0) , _topindex(-1) {} void Push(const T& x){ //入棧 if (_topindex + 1 == _capacity){ //判斷是否需要開辟空間 _capacity = 2 * _capacity + 3; T* tmp = new T(_capacity); if (tmp == NULL){ cout << "failed new" << endl; exit(-1); } memcpy(tmp, _array, sizeof(T)*(_topindex + 1)); //內置類型使用 delete _array; // memcpy ,自定義 _array = tmp; //使用for循環逐個拷貝 } //注意深拷貝和前拷貝 _array[++_topindex] = x; } void Pop(){ //出棧 if (_topindex > -1){ cout << _array[_topindex] << endl; _topindex--; } } bool empty(){ //清空棧 return _topindex = -1; } };