c++学习笔记之类模板

类是对象的抽象,类模板是类的抽象。

比较两个数(不同类型)的大小

在类模板内定义成员函数

#include<iostream>
using namespace std;
template<class numtype>
class compare
{
	public:
		compare(numtype a,numtype b)
		{
			x=a;y=b;
		}
		numtype max()
		{
			return(x>y)?x:y;
		}
		numtype min()
		{
			return(x<y)?x:y;
		}
		private:
			numtype x,y;
 } ;
 int main()
 {
 	compare<int> cmp1(3,7);
 	cout<<cmp1.max()<<"is the maximum of two integer numbers"<<endl;
 	cout<<cmp1.min()<<"is the minimum of two integer numbers"<<endl<<endl;
 	compare<float>cmp2(45.78,93.6);
 	cout<<cmp2.max()<<"is the maximum of two float numbers"<<endl;
 	cout<<cmp2.min()<<"is the minimum of two float numbers"<<endl<<endl;
 	compare<char>cmp3('a','A');
 	cout<<cmp3.max()<<"is the maximum of two characters"<<endl;
 	cout<<cmp3.min()<<"is the minimum of two characters"<<endl<<endl;
 }

在类模板外定义成员函数

#include<iostream>
using namespace std;
template<class numtype>
class compare
{
	public:
		compare(numtype a,numtype b);
		numtype max();
		numtype min();
	private:
		numtype x,y;
 } ;
 template <class numtype>
 compare<numtype>::compare(numtype a,numtype b)
 {
 	x=a;y=b;
 }
 template<class numtype>
 numtype compare<numtype>::max()
 {
 	return (x>y)?x:y;
 }
 template<class numtype>
 numtype compare<numtype>::min()
 {
 	return(x<y)?x:y;
 }
 int main()
 {
 	compare<int> cmp1(3,7);
 	cout<<cmp1.max()<<"is the maximum of two integer numbers"<<endl;
 	cout<<cmp1.min()<<"is the minimum of two integer numbers"<<endl<<endl;
 	compare<float>cmp2(45.78,93.6);
 	cout<<cmp2.max()<<"is the maximum of two float numbers"<<endl;
 	cout<<cmp2.min()<<"is the minimum of two float numbers"<<endl<<endl;
 	compare<char>cmp3('a','A');
 	cout<<cmp3.max()<<" is the maximum of two characters"<<endl;
 	cout<<cmp3.min()<<" is the minimum of two characters"<<endl<<endl;
 }

猜你喜欢

转载自blog.csdn.net/qq_24163555/article/details/84334329