赞
踩
转 :http://see.xidian.edu.cn/cpp/biancheng/view/213.html
有时,有两个或多个类,其功能是相同的,仅仅是数据类型不同,如下面语句声明了一个类:
-
-
- class Compare_int{public : Compare(int a,int b) { x=a; y=b; } int max( ) { return (x>y)?x:y; } int min( ) { return (x<y)?x:y; }private : int x,y;};
-
-
- class Compare_float{public : Compare(float a,float b) { x=a;y=b; } float max( ) { return (x>y)?x:y; } float min( ) { return (x<y)?x:y; }private : float x,y;}
-
-
- template <class numtype> //声明一个模板,虚拟类型名为numtypeclass Compare //类模板名为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,y;};
-
-
- #include <iostream>using namespace std;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,y;};int main( ){ Compare<int > cmp1(3,7); //定义对象cmp1,用于两个整数的比较 cout<<cmp1.max( )<<" is the Maximum of two integer numbers."<<endl; cout<<cmp1.min( )<<" is the Minimum of two integer numbers."<<endl<<endl; Compare<float > cmp2(45.78,93.6); //定义对象cmp2,用于两个浮点数的比较 cout<<cmp2.max( )<<" is the Maximum of two float numbers."<<endl; cout<<cmp2.min( )<<" is the Minimum of two float numbers."<<endl<<endl; Compare<char> cmp3(′a′,′A′); //定义对象cmp3,用于两个字符的比较 cout<<cmp3.max( )<<" is the Maximum of two characters."<<endl; cout<<cmp3.min( )<<" is the Minimum of two characters."<<endl; return 0;}
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。