tsaiwn@ccbsd3 % cat -n mystk3.h 1 //mystk3.h 2 //a template class for a STACK, CopyLeft by tsaiwn@csie.nctu.edu.tw 3 // 這範例是把之前的 STACK 範例重新寫成 template class(樣版類別); 4 // 寫成非template 則會分 .h(宣告) 與 .cpp(實作); 5 // 寫成 template 時只寫成一個 .h 檔; //注意以下 template class 寫法! 6 // 除了在 class 之前要寫 template < class T> 之外, 7 // 所有寫在 class{ }; 結構之外的函數的左邊(前面)也都要寫 template 8 // 而且在 :: 之左也要寫 類別, 例如 ... MyStack:: ... 9 // 還有, function 內該換的 type 也別忘了換成 T 10 template 11 class MyStack{ 12 public: 13 enum{NELEMENT=99}; 14 private: 15 GG data[NELEMENT]; 16 int stkptr; 17 public: 18 MyStack(void){ stkptr= -1; } 19 void push(GG x); 20 void pop(void); 21 GG top(void); 22 int empty(void){ return (stkptr <= -1) ;} 23 int isfull(void){ return (stkptr >= NELEMENT-1);} 24 }; 25 template GG MyStack :: top(void) 26 { // 注意上列的寫法 ! 27 if(stkptr > -1) return data[stkptr]; // 有防呆一下喔 28 } 29 template 30 void MyStack :: push(GG x) { data[++stkptr] = x; } 31 //Actually, pop( ) function is a void function in C++ STL 32 template 33 void MyStack ::pop(void) { if(stkptr > -1) --stkptr; } tsaiwn@ccbsd3 % cat -n mymain3.cpp 1 // mymain3.cpp; g++ mymain3.cpp ; ./a.out 2 #include "mystk3.h" 3 //注意以下 iostream.h 為舊的寫法; 1999之後的 C++ 使用 4 #include 5 using namespace std; // 新#include 的寫法要用到 namesapce std 6 int main( ) { 7 MyStack x; 8 MyStack y; 9 x.push(880); 10 x.push(770); 11 x.push(53); 12 while(!x.empty()){ 13 cout << x.top(); y.push( x.top() + 0.5 ); 14 x.pop(); 15 } 16 cout << endl << "=== === now dump y:\n"; 17 while(!y.empty()){ 18 cout << y.top() << " "; y.pop(); 19 } 20 cout << "\n=== bye bye ===" << endl; 21 return 0; // normal return 22 } tsaiwn@ccbsd3 % g++ mymain3.cpp -Wno-deprecated tsaiwn@ccbsd3 % ./a.out 53770880 === === now dump y: 880.5 770.5 53.5 === bye bye === tsaiwn@ccbsd3 % exit exit