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> //声明一个模板,虚拟类型名为numtype
class 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;
};
template <class 类型参数名>
Compare_int cmp1(4,7); // Compare_int是已声明的类
Compare cmp(4,7); // Compare是类模板名
Compare <int> cmp(4,7);
#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;
}
7 is the Maximum of two integers. 3 is the Minimum of two integers. 93.6 is the Maximum of two float numbers. 45.78 is the Minimum of two float numbers. a is the Maximum of two characters. A is the Minimum of two characters.
numtype Compare::max( ) {…} //不能这样定义类模板中的成员函数
template <class numtype>
numtype Compare<numtype>::max( )
{
return (x>y)?x:y;
}
template <class 虚拟类型参数>
template <class numtype> //注意本行末尾无分号
class Compare
{…}; //类体
类模板名<实际类型名> 对象名; 类模板名<实际类型名> 对象名(实参表列);
Compare<int> cmp; Compare<int> cmp(3,7);
template <class 虚拟类型参数>
函数类型 类模板名<虚拟类型参数>::成员函数名(函数形参表列) {…}
template <class T1,class T2>
class someclass
{…};
someclass<int,double> obj;
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有