模板类以这样的代码开头:template<class Type>
class看作是变量的类型名,该变量接受类型作为其值,把Type看作是该变量的名称;
将模板信息放在一个头文件中,建立stacktp.h
1 #ifndef STACKTP_H_ 2 #define STACKTP_H_ 3 // 建立模板 4 5 template<class Type> 6 class Stack 7 { 8 private: 9 enum {MAX=10}; 10 Type items[MAX]; 11 int top; 12 public: 13 Stack(); 14 bool isempty(); 15 bool isfull(); 16 bool push(const Type & item); 17 bool pop(Type & item); 18 }; 19 20 template<class Type> 21 Stack<Type>::Stack() 22 { 23 top=10; 24 } 25 template<class Type> 26 bool Stack<Type>::isempty() 27 { 28 return top==0; 29 } 30 template<class Type> 31 bool Stack<Type>::isfull() 32 { 33 return top==MAX; 34 } 35 template<class Type> 36 bool Stack<Type>::push(const Type &item) 37 { 38 if(top<MAX) 39 { 40 items[top++]=item; 41 return true; 42 } 43 else 44 return false; 45 } 46 template<class Type> 47 bool Stack<Type>::pop(Type & item) 48 { 49 if(top>0) 50 { 51 item=items[--top]; 52 return true; 53 } 54 else 55 return false; 56 } 57 58 #endif
建立源文件stacktem.cpp;
1 #include<iostream> 2 #include<string> 3 #include<cctype> 4 #include"stacktp.h" 5 6 using namespace std; 7 int main() 8 { 9 Stack<string> st;// 创建一个空的stack,和前面的模板联系起来 10 char ch; 11 string po; 12 cout<<"Please enter A to add a purchase order. " 13 <<"P to precess a PO,or Q to quit."<<endl; 14 while(cin>>ch && toupper(ch)!='Q' ) 15 { 16 while(cin.get()!=' ') 17 { 18 continue; 19 } 20 if(!isalpha(ch)) 21 { 22 cout<<'a'; 23 continue; 24 } 25 switch(ch) 26 { 27 case 'A': 28 case 'a':cout<<"Enter a PO number to add:"<<endl; 29 cin>>po; 30 if(st.isfull()) 31 { 32 cout<<"stack already full"<<endl; 33 } 34 else 35 { 36 st.push(po); 37 } 38 break; 39 case 'P': 40 case 'p': 41 if(st.isempty()) 42 { 43 cout<<"stack already empty"<<endl; 44 } 45 else 46 { 47 st.pop(po); 48 cout<<"PO #"<<po<<" popped "; 49 break; 50 } 51 } 52 cout<<"Please enter A to add a purchase order, " 53 <<"P to process a PO,or Q to quit. "; 54 } 55 cout<<"Bye!"<<endl; 56 57 return 0; 58 }
下面为代码调试运行结果: