1 #include<iostream> 2 3 template<class T> 4 class Stack 5 { 6 private: 7 int top; 8 T* base; 9 int size; 10 T* elements; 11 public: 12 Stack<T>(int sz):size(sz),top(-1) 13 { 14 base = new T[sz]; 15 if(!base) 16 std::cout << "momoryAllocationError" << std::endl; 17 elements = base; 18 } 19 ~Stack<T>() 20 { delete[] base; } 21 bool IsEmpty() const 22 { return static_cast<bool>(top == -1); } 23 bool IsFull() const 24 { return static_cast<bool>(top == size - 1); } 25 void Push(const T item); 26 T Pop(); 27 void disp(); 28 void Destory(); 29 }; 30 31 template<class T> 32 void Stack<T>::Push(const T item) 33 { 34 if(top == size - 1) 35 std::cout << "Stack is full" << std::endl; 36 else 37 { 38 top++; 39 *(elements + top) = item; 40 } 41 } 42 43 template<class T> 44 T Stack<T>::Pop() 45 { 46 if(top == -1) 47 std::cout << "Stack is empty" << std::endl; 48 T item = *(elements + top); 49 top--; 50 return item; 51 } 52 53 template<class T> 54 void Stack<T>::disp() 55 { 56 int p = top; 57 std::cout << "*****数据输出*****" << std::endl; 58 while(p + 1) 59 { 60 std::cout << *(elements + p) << std::endl; 61 p--; 62 } 63 std::cout << "*****输出结束*****" << std::endl; 64 } 65 66 template<class T> 67 void Stack<T>::Destory() 68 { 69 ~Stack<T>(); 70 }