C++之类模板

/*
类模板的使用:
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;
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值