//mystk3.h //a template class for a STACK, CopyLeft by tsaiwn@csie.nctu.edu.tw // 這範例是把之前的 STACK 範例重新寫成 template class(樣版類別); // 寫成非template 則會分 .h(宣告) 與 .cpp(實作); // 寫成 template 時只寫成一個 .h 檔; //注意以下 template class 寫法! // 除了在 class 之前要寫 template < class T> 之外, // 所有寫在 class{ }; 結構之外的函數的左邊(前面)也都要寫 template // 而且在 :: 之左也要寫 類別, 例如 ... MyStack:: ... // 還有, function 內該換的 type 也別忘了換成 T template class MyStack{ public: enum{NELEMENT=99}; private: GG data[NELEMENT]; int stkptr; public: MyStack(void){ stkptr= -1; } void push(GG x); void pop(void); GG top(void); int empty(void){ return (stkptr <= -1) ;} int isfull(void){ return (stkptr >= NELEMENT-1);} }; template GG MyStack :: top(void) { // 注意上列的寫法 ! if(stkptr > -1) return data[stkptr]; // 有防呆一下喔 } template void MyStack :: push(GG x) { data[++stkptr] = x; } //Actually, pop( ) function is a void function in C++ STL template void MyStack ::pop(void) { if(stkptr > -1) --stkptr; }