类模板的是为了解决这么一类问题存在的:当代码里面需要定义多个类似的类,而这些类中只有基本数据格式不一样或某个类参数不一样。类模板可以提高代码的简洁性。下面是随意的三个模板: 模板一: template <class numtype> class compare { public: compare(numtype a,numtype b){ x = a; y = b; } numtype max(){ return (x>y)?x:y ; } numtype min(){ return (x<y)?x:y ; } private: numtype x; numtype y; }; 模板二: template <class A, class B> class outmy{ public: outmy(A a,B b){ x = a; y = b; } public: A Big(){ cout<<"Big = "<<x<<endl; return x; } B Comfux(){ cout<<"Comfux = "<<y<< endl; return y; } private: A x; B y; };模板三: template <class A, int Asize> class Arraymy{ public: A PrintArry(){ for (int i=0 ; i<Asize; i++ ) { cout<<"value ="<<myarry[i]<<endl; ret=myarry[i]; } return ret; } A IniArry(){ for (int i=0 ; i<Asize; i++ ) { cout<<"input:"<<endl; cin>>myarry[i]; ret=myarry[i]; } return ret; } private: A myarry[Asize]; A ret; }; 如下是使用: int main(void){ //template 1: compare < int > cmp(4,6); int a=cmp.max(); int b=cmp.min(); cout<<"max = "<<a<<endl; cout<<"min = "<<b<<endl; //template 2: outmy< int, double > myo(6,5.5); int c = myo.Big(); double d = myo.Comfux(); //template 3: Arraymy< int, 5 > mya; a=mya.IniArry(); b=mya.PrintArry(); getchar();//getchar是为了防止console退出 getchar();//getchar是为了防止console退出 return 0; }