c++类模板

1函数模板

#include<iostream>
using namespace std;
template <typename T>
T max(T a,T b,T c)
{
	if(a<b)a=b;
	if(a<c)a=c;
		return a;
		
}
int main()
{
	int i;float f;double d;
	int i1=44,i2=33, i3=55;
	float f1=324.1, f2=12.324, f3=454.1;
	double d1=1.23234, d2=3.32423, d3=35.234;
	i=max(i1,i2,i3);
	f=max(f1,f2,f3);
	d=max(d1,d2,d3);
	cout<<i<<" "<<f<<" "<<d<<endl;
	return 0;
}

2类模板(类内定义方法)

#include<iostream>
using namespace std;
template<class T>
class compare
{
	public:
		compare(T a,T b)
		{
			h=a;
			w=b;
		}
		T min()
		{
			return(h>w)?w:h;
		}
		T max()
		{		
			return(h>w)?h:w;
		}
	private:
		T h;
		T w;
};

int main()
{	int i;float f;
	compare<int> c1(3,6);
	i=c1.min();
	cout<<i<<endl;
	i=c1.max();
	cout<<i<<endl;
	compare<float> c2(4.31,65.1);
	f=c2.min();
	cout<<f<<endl;
	f=c2.max();
	cout<<f<<endl;
	return 0;
}

2类模板(类外定义方法)

#include<iostream>
using namespace std;
template<class T>
class compare
{
	public:
		compare(T a,T b);
		T min();
		T max();
	private:
		T h;
		T w;
};

template<class T>
compare<T>::compare(T a,T b)
{
	h=a;
	w=b;
}

template<class T>
T compare<T>::min()
{
	if(h<w)
		return h;
	return w;
}

template<class T>
T compare<T>::max()
{
	if(h<w)
		return w;
	return h;
}
int main()
{	int i;float f;
	compare<int> c1(3,6);
	i=c1.min();
	cout<<i<<endl;
	i=c1.max();
	cout<<i<<endl;
	compare<float> c2(4.31,65.1);
	f=c2.min();
	cout<<f<<endl;
	f=c2.max();
	cout<<f<<endl;
	return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值