/*
类模板的使用:
1.用类模板定义对象的形式:
类模板名<实际类型名> 对象名; Compare<int> cmp;
类模板名<实际类型名> 对象名(实参表列); Compare<int> cmp(2,4);
2.在类模板外定义成员函数:
一般形式:
template<class 虚拟类型参数>
函数类型 类模板名<虚拟类型参数>::成员函数名(函数形参表列){...}
*/
#include <iostream>
using namespace std;
template<class numtype> //虚拟类型名为numtype
class Compare//类模板名为Compare
{
private:
numtype x, y;
public:
Compare(numtype a, numtype b); //构造函数声明
numtype max(); //成员函数1的声明
numtype min() //成员函数2
{
return (x < y)? x : y;
}
};
template<class numtype> //构造函数的定义
Compare<numtype>::Compare(numtype a, numtype b)
{
x = a;
y = b;
}
template<class numtype> //成员函数1的定义
numtype Compare<numtype>::max()
{
return x > y? x : y;
}
int main()
{
Compare<int> cmp1(1,3);
cout << cmp1.max() << endl;
cout << cmp1.min() << endl;
Compare<char> cmp2('a','A');
cout << cmp2.max() << endl;
cout << cmp2.min() << endl;
return 0;
}
C++之类模板
最新推荐文章于 2024-07-18 22:54:13 发布