声明一个类模板
1 #include <iostream> 2 3 /* run this program using the console pauser or add your own getch, system("pause") or input loop */ 4 using namespace std; 5 template<class numtype> 6 class Compare 7 { 8 public: 9 Compare(numtype a,numtype b) 10 { 11 x=a; 12 y=b; 13 } 14 numtype max() 15 { 16 return (x>y)?x:y; 17 } 18 numtype min() 19 { 20 return (x<y)?x:y; 21 } 22 private: 23 numtype x,y; 24 }; 25 int main(int argc, char** argv) { 26 Compare<int>cmp1(3,7); 27 cout<<cmp1.max()<<"is the Maximum of two integer numbers."<<endl; 28 cout<<cmp1.min()<<"is the Minimum of two integer numbers."<<endl<<endl; 29 Compare<float> cmp2(45.78,93.6); 30 cout<<cmp2.max()<<"is the Maximum of two float numbers."<<endl; 31 cout<<cmp2.min()<<"is the Minimum of two float numbers"<<endl<<endl; 32 Compare<char>cmp3('a','A'); 33 cout<<cmp3.max()<<"is the Maximum of two characters."<<endl; 34 cout<<cmp3.min()<<"is the Minimum of two characters."<<endl; 35 return 0; 36 }