c++使用模板(template)封裝Stack

 1 #include <iostream>
 2 template<class Type>
 3 class Stack  4 {  5     public:  6         Stack(int MaxStackSize=100);  7         bool IsFull();  8         bool IsEmpty();  9         void StackFull(); 10         void StackEmpty(); 11         void Push(const Type& x); 12         Type Pop(Type& x); 13     private: 14         int top; 15         Type * stack; 16         int MaxSize; 17 }; 18 template<class Type>
19 Stack<Type>::Stack(int MaxStackSize):MaxSize(MaxStackSize)//構造函數 
20 { 21     stack = new Type[MaxSize]; 22     top = -1; 23 } 24 template<class Type>
25 inline bool Stack<Type>::IsFull()//判斷棧滿 
26 { 27     if(top == MaxSize-1) return true; 28     else return false; 29 } 30 template<class Type>
31 inline bool Stack<Type>::IsEmpty()//判斷棧空 
32 { 33     if(top == -1) return true; 34     else return false; 35 } 36 template<class Type>
37 void Stack<Type>::StackFull() 38 { 39     std::cout<<"StackFull,PushFail\n"; 40 } 41 template<class Type>
42 void Stack<Type>::StackEmpty() 43 { 44     std::cout<<"StackEmpty,PopFail\n"; 45 } 46 template<class Type>
47 void Stack<Type>::Push(const Type& x)//入棧 
48 { 49     if(IsFull()) StackFull(); 50     else stack[++top] = x; 51 } 52 template<class Type>
53 Type Stack<Type>::Pop(Type& x)//出棧 
54 { 55     if(IsEmpty()) 56  { 57  StackEmpty(); 58         return -1; 59  } 60     x = stack[top--]; 61     return x; 62 } 63 int main(int argc, char** argv)//測試代碼 
64 { 65     Stack<int> S(100);//實例化空間大小爲100的棧 
66     for(int i=0;i<10;i++) 67         S.Push(i);//將從0-9的數入棧 
68     int tmp; 69     while(!S.IsEmpty())//出棧 
70  { 71         std::cout<<S.Pop(tmp)<<std::endl; 72  } 73     std::cout<<S.Pop(tmp)<<std::endl; 74     return 0; 75 }
相關文章
相關標籤/搜索