將例9.14改寫爲在類模版外定義各成員函數

 

  1. #include<iostream>  
  2. using namespace std;  
  3.  
  4. template <class numtype>  
  5. class Compare  
  6. {  
  7. public:  
  8.     Compare(numtype a,numtype b);  
  9.  
  10.     numtype max();  
  11.  
  12.     numtype min();  
  13.  
  14. private:  
  15.     numtype x,y;  
  16. };  
  17.  
  18. template<class numtype>  
  19. Compare<numtype>::Compare(numtype a,numtype b)  
  20. { x=a;y=b; }  
  21.  
  22. template<class numtype>  
  23. numtype Compare<numtype>::max()  
  24. {  
  25.     return (x>y)? x:y;  
  26. }  
  27.  
  28. template<class numtype>  
  29. numtype Compare<numtype>::min()  
  30. {  
  31.     return (x<y)? x:y;  
  32. }  
  33. int main()  
  34. {  
  35.     Compare<int>cmp1(3,7);  
  36.     cout<<cmp1.max()<<"整數"<<endl;  
  37.     cout<<cmp1.min()<<"整數"<<endl<<endl;  
  38.     Compare<float>cmp2(45.78,93.6);  
  39.     cout<<cmp2.max()<<"浮點"<<endl;  
  40.     cout<<cmp2.min()<<"浮點"<<endl<<endl;  
  41.     Compare<char>cmp3('a','A');  
  42.     cout<<cmp3.max()<<"字符"<<endl;  
  43.     cout<<cmp3.min()<<"字符"<<endl;  
  44.     return 0;  
  45. }  

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章