(一)函数的重载
1、定义:C++允许用同一函数名定义多个函数,即对一个函数名重新赋予它新的含义,使一个函数名可以多用。
2、重载的函数的参数个数、参数类型、参数顺序这3者至少要有一个不同;而函数返回值和函数体可以相同,也可以不同。
【例1】 求3个数中最大的数(分别考虑整数、双精度数、长整数的情况)
#include<iostream>
using namespace std;
int main()
{
int max(int a,int b,int c);
double max(double a,double b,double c);
long max(long a,long b,long c);
int i1,i2,i3,i;
cin>>i1>>i2>>i3;
i=max(i1,i2,i3);
cout<<"i_max="<<i<<endl;
double d1,d2,d3,d;
cin>>d1>>d2>>d3;
d=max(d1,d2,d3);
cout<<"d_max=" <<d<<endl;
long g1,g2,g3,g;
cin>>g1>>g2>>g3;
g=max(g1,g2,g3);
cout<<"g_max="<<g<<endl;
return 0;
}
int max(int a,int b,int c)
{
if(b>a) a=b;
if(c>a) a=c;
return a;
}
double max(double a,double b,double c)
{
if(b>a) a=b;
if(c>a) a=c;
return a;
}
long max(long a,long b,long c)
{
if(b>a) a=b;
if(c>a) a=c;
return a;
}

【例2】编写一个程序,用来求两个整数或3个整数中的最大数。如果输入两个整数,程序就输出这两个整数中的最大数,如果输入3个整数,程序就输出这3个整数中的最大数。
#include <iostream>
using namespace std;
int main()
{
int max(int a,int b,int c);
int max(int a,int b);
int a=8,b=-12,c=27;
cout<<"max(a,b,c)="<<max(a,b,c)<<endl;
cout<<"max(a,b)="<<max(a,b)<<endl;
}
int max(int a,int b,int c)
{
if(b>a) a=b;
if(c>a) a=c;
return a;
}
int max(int a,int b)
{
if(a>b) return a;
else return b;
}

===================================================================================================================
(二)函数模板(function template)
1、定义:建立一个通用函数,其函数类型和形参类型不具体制定,用一个虚拟的类型来代表。
2、一般形式:
template<typename/class T>
通用函数定义
注:1)typename与class 用法是一样的,其中typename是不久前加到标准c++中的,建议使用typename;T是习惯性写法,也可以用其他来代替。
2)类型参数可以有多个(按需求来确定)
3)它只适用于函数的参数个数和函数体相同,但类型不同的情况。
【例3】将例1程序改为通过函数模板来实现
#include<iostream>
using namespace std;
template<typename T>
T max(T a,T b,T c)
{
if(b>a) a=b;
if(c>a) a=c;
return a;
}
int main()
{
int i1=185,i2=-76,i3=567,i;
double d1=56.87,d2=90.23,d3=-3214.78,f;
long g1=67854,g2=-912456,g3=673456,g;
i=max(i1,i2,i3);
f=max(d1,d2,d3);
g=max(g1,g2,g3);
cout<<"i_max="<<i<<endl;
cout<<"f_max="<<f<<endl;
cout<<"g_max="<<g<<endl;
return 0;
}
