类模板-template

template是声明各模板的关键字,表示声明一个模板,模板参数可以是一个,也可以是多个。

声明类模板要增加一行: template<class 类型参数名>
如template<class dataType>其中的类型参数名为虚拟的类型参数名,以后会被实际的类型名替代。如例子中的dataType将会被int,float,char等替代。

class Compare_int
{
	private:
		int x,y;
	public:
		Compare(int a,int b)
		{
			x=a;
			y=b;
		}
		int getMax()
		{
			return (x>y)? x:y;
		}
};

class Compare_float
{
	private:
		float x,y;
	public:
		Compare(float a,float b)
		{
			x=a;
			y=b;
		}
		float getMax()
		{
			return (x>y)? x:y;
		}
};

class Compare_float
{
	private:
		float x,y;
	public:
		Compare(float a,float b)
		{
			x=a;
			y=b;
		}
		float getMax()
		{
			return (x>y)? x:y;
		}
};

用一个类模板减少重复性的工作:

template<class dataType>
class Compare
{
	private:
		dataType x,y;
	public:
		Compare(dataType a,dataType b)
		{
			x=a;
			y=b;
		}
		dataType getMax()
		{
			return (x>y)? x:y;
		}
};

实例化时必须用实际的类型名去替代虚拟的类型,如Compare<int> cmp1(3,7);
完整代码:

#include <iostream>

using namespace std;

template<class dataType>
class Compare
{
	private:
		dataType x,y;
	public:
		Compare(dataType a,dataType b)
		{
			x=a;
			y=b;
		}
		dataType getMax()
		{
			return (x>y)? x:y;
		}
};

int main()
{
	Compare<int> cmp1(3,7);
	cout<<cmp1.getMax()<<" is the Maximum of two Integer numbers"<<endl;

	Compare<float> cmp2(12.3,23.4);
	cout<<cmp2.getMax()<<" is the Maximun of two Float numbers"<<endl;

	Compare<char> cmp3('a','b');
	cout<<cmp3.getMax()<<" is the Maximun of two Char numbers"<<endl;

	return 0;
}


  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值