0
点赞
收藏
分享

微信扫一扫

类模板内、外定义成员函数

秀儿2020 2022-04-26 阅读 132
c++

1.类模板内定义各成员函数
(1)参考代码

 #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);          //定义对象cmp1,用于两个整数的比较
	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);   //定义对象cmp2,用于两个浮点数的比较
	cout << cmp2.max() << "is the Maximum of two float numbers." << endl;
	cout << cmp2.min() << "is the Minimum of two float numbers. " << endl;
	Compare<char> cmp3('a','A');         //定义对象cmp3,用于两个字符的比较
	cout << cmp3.max() << "is the Maximum of two characters. " << endl;
	cout << cmp3.min() << " is the Minimum of two characters. " << endl;
	return 0;
}

(2)运行结果
类模板内定义成员函数

2. 类模板外定义各成员函数
(1)参考代码

#include <iostream>
using namespace std;
template<class type>     //定义类模板
class Compare
{
public:
	
	Compare(type a, type b)
	{
		x = a; y = b;
	}
	type max();
	
	type min();
	
private:
	 type x, y;
};

template<class type>
type Compare<type>::max()
{

	return(x > y) ? x : y;
}
template<class type>
type Compare<type>::min()
{
	return(x < y) ? x : y;
}

int main()
{
	Compare<int> cmp1(3, 7);          //定义对象cmp1,用于两个整数的比较
	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);   //定义对象cmp2,用于两个浮点数的比较
	cout << cmp2.max() << " is the Maximum of two float numbers." << endl;
	cout << cmp2.min() << " is the Minimum of two float numbers. " << endl;
	Compare<char> cmp3('a', 'A');         //定义对象cmp3,用于两个字符的比较
	cout << cmp3.max() << " is the Maximum of two characters. " << endl;
	cout << cmp3.min() << " is the Minimum of two characters. " << endl;
	return 0;
}

(2)运行结果
在这里插入图片描述

举报

相关推荐

0 条评论