www.gusucode.com > 《C++高级语言程序设计》PPT及全书例子源代码-源码程序 > 《C++高级语言程序设计》PPT及全书例子源代码-源码程序/code/C++例题程序/第5章/s5_2/smain5_2.cpp

    //Download by http://www.NewXing.com
//smain5_2.cpp
//具有函数模板和同名重载函数的匹配过程

#include <iostream>

using namespace std;

int GetMax( int a, int b )					//求两个整型数的最大值
{
	cout << "调用int,maxValue =  "; 		//用于显示所调用的函数
	return ( a > b ) ? a : b;
}

long GetMax( long a, long b )				//求两个长整型数的最大值
{
	cout << "调用long,maxValue =  ";
	return ( a > b ) ? a : b;
}


double GetMax( double a, double b )			//求两个双精度型数的最大值
{
	cout << "调用double,maxValue =  ";
	return ( a > b ) ? a : b;
}

//注释掉该函数,主要是看看GetMax( 'A', '2' )调用了哪一个函数
//char GetMax( char a, char b )				//求两个字符型数的最大值
//{
//	cout << "调用char,maxValue =  ";
//	return ( a > b ) ? a : b;
//}

//定义函数模板1
//在这里之所以在函数模板中添加第三参数char *,目的是为了与函数模板2区分开
template <class Type>
Type GetMax( Type a[ ], int iCnt, char *lpszArrayName )
{
	int i;									//定义数组下标变量i
	Type tMaxValue = a[0];					//定义Type类型的变量
	for ( i=1; i<iCnt; i++ )				//在循环中寻找数组中最大的值
	{
		if ( tMaxValue < a[i] )
		{
			tMaxValue = a[i];				//保存最大值到tMaxValue
		}
	}
	cout << "使用函数模板1," << lpszArrayName << "的最大值,maxValue =  ";
	return tMaxValue;
}

//定义函数模板2
template <class TypeX, class TypeY>
TypeX GetMax( TypeX tX, TypeY tY )
{
	TypeX tMaxValue = 0;			//定义一个TypeX类型变量
	if ( tX > ( TypeX )tY )			//比较前,首先将TypeY类型变量转化为TypeX类型变量
	{
		tMaxValue = tX;
	}
	else
	{
		tMaxValue = ( TypeX )tY;
	}
	cout << "调用函数模板2,maxValue =  ";
	return tMaxValue;
}


//主函数
void main( )
{ 
	int a[ ] = {1, 3, 5, 7, 9, 6, 4, 8, 2, 10};
	double b[ ] = {3.2, -6.4, 6.0, 9.9, 8.6, 2.1};
	char c[ ] = {'A', 'C', '1', 'a', 'c'};

	cout << "	" << GetMax( a, 10, "数组a" ) << endl;	//使用函数模板1
	cout << "	" << GetMax( b, 5, "数组b" ) << endl; 	//使用函数模板1  
	cout << "	" << GetMax( c, 5, "数组c" ) << endl;	//使用函数模板1

	cout << "	" << GetMax( 10, 20 ) << endl;			//调用重载函数
	cout << "	" << GetMax( 101L, 201L ) << endl;		//调用重载函数
	cout << "	" << GetMax( 1.0, 2.0 ) << endl;		//调用重载函数

	cout << "char=" << GetMax( 'A', '2' ) << endl;		//使用函数模板2

	cout << "	" << GetMax( 10, 5.0 ) << endl;			//使用函数模板2
	cout << "	" << GetMax( 11.1, 5 ) << endl;			//使用函数模板2
	cout << "	" << GetMax( 22, 10L ) << endl;			//使用函数模板2
	cout << "	" << GetMax( 'A', 2L ) << endl;			//使用函数模板2	
	cout << "	" << GetMax( 1.0, 200L ) << endl;		//使用函数模板2
	cout << "	" << GetMax( 100.0, 'A' ) << endl;		//使用函数模板2

	cin.get( );  
}