类模板的用法
1.格式:template<模板参数表> (参数可以直接定义默认值)
class 类名
{ ...};
其成员函数可以在类外定义。
eg:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 template <class TNO,class TScore=int,int num=10> 2 class S 3 { 4 private: 5 TNO Sid[num]; 6 public: 7 int bel(TScore ascore); 8 void sort(); 9 }; 10 template <class TNO,class TScore,int num> 11 int S <TNO,TScore,num>::bel(TScore ascore) 12 { 13 return 0; 14 } 15 template <class TNO,class TScore,int num> 16 void S <TNO,TScore,num>::sort() 17 { 18 return Sid[0]; 19 }
2.栈类模板的实现:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include <iostream> 2 using namespace std; 3 4 template <class T> 5 class Stack 6 { 7 private: 8 int size; 9 int top; 10 T* space; 11 public: 12 Stack(int=10); 13 ~Stack() 14 { 15 delete []space; 16 } 17 bool push(const T&); 18 T pop(); 19 bool IsEmpty() const 20 { 21 return top==size; 22 } 23 bool IsFull() const 24 { 25 return top==0; 26 } 27 }; 28 template <class T> 29 Stack <T>::Stack(int size) 30 { 31 this->size=size; 32 space=new T[size]; 33 top=size; 34 } 35 template <class T> 36 bool Stack<T>::push(const T& element) 37 { 38 if(!IsFull()) 39 { 40 space[--top]=element; 41 return true; 42 } 43 return false; 44 } 45 template <class T> 46 T Stack<T>::pop() 47 { 48 return space[top++]; 49 } 50 int main() 51 { 52 Stack<char> S1(4); 53 S1.push('x'); 54 S1.push('y'); 55 S1.push('z'); 56 S1.push('u'); 57 S1.push('v'); 58 while(!S1.IsEmpty()) 59 cout<<S1.pop()<<endl; 60 return 0; 61 }