#include <iostream>
using namespace std;
template <class numtype>//声明类模板,虚拟类型名为numtype
class Compare//类模板名为Compare
{
public:
Compare(numtype a,numtype b)//定义构造函数
{
x=a;y=b;
}
numtype max()//函数类型暂定为numtype
{
return (x>y)?x:y;
}
numtype min()//函数类型暂定为numtype
{
return (x<y)?x:y;
}
private:
numtype x,y;//数据类型暂定为numtype
};
int main()
{
Compare<int>cp1(3,7);//定义对象cp1,用于两个整数的比较
cout<<cp1.max()<<" is the maximum of the two integer numbers. "<<endl;
cout<<cp1.min()<<" is the minimum of the two interger numbers."<<endl;
Compare<float>cf2(45.78,93.6);
cout<<cf2.max()<<" is the maximum of the two integer numbers."<<endl;
cout<<cf2.min()<<" is the minimum of the two interger numbers."<<endl;
Compare<char>c3('a','A');
cout<<c3.max()<<" is the maximum of the two integer numbers."<<endl;
cout<<c3.min()<<" is the minimum of the two interger numbers."<<endl;
return 0;
}
类模板
最新推荐文章于 2025-03-29 00:04:13 发布