C++中模板template和類class的結合使用


模板類以這樣的代碼開頭: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.\n"
13         <<"P to precess a PO,or Q to quit."<<endl;
14     while(cin>>ch && toupper(ch)!='Q' )
15     {
16         while(cin.get()!='\n')
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\n";
49                 break;
50             }
51         }
52         cout<<"Please enter A to add a purchase order,\n"
53             <<"P to process a PO,or Q to quit.\n";
54     }
55     cout<<"Bye!"<<endl;
56 
57         return 0;
58 }

下面為代碼調試運行結果:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM