1.所谓函数的重载是指完成不同功能的函数可以具有相同的函数名。
- C++编译器根据函数的实参来确定应该调用哪一个函数
- 例:
int fun(int a, int b)
{
return a+b;
}
int fun (int a)
{
return a*a;
}
void main(void)
{
cout<<fun(3,5)<<endl;
cout<<fun(5)<<endl;
}
2.定义的重载函数必须有不同的参数个数,或不同的参数类型(不同的参数顺序)。只有这样编译系统才有可能根据不同的参数取调用不同的重载函数。
3.仅返回值不同时,不能定义为重载函数。仅函数的类型不同,不能定义为重载函数
4.重载函数不要求函数体相同。
5.例:求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; //输入3个整数
i=max(i1,i2,i3); //求3个整数中的最大者
cout<<″i_max=″<<i<<endl;
double d1,d2,d3,d;
cin>>d1>>d2>>d3; //输入3个双精度数
d=max(d1,d2,d3); //求3个双精度数中的最大者
cout<<″d_max=″<<d<<endl;
long g1,g2,g3,g;
cin>>g1>>g2>>g3; //输入3个长整数
g=max(g1,g2,g3); //求3个长整数中的最大者
cout<<″g_max=″<<g<<endl;
}
int max(int a,int b,int c) //定义求3个整数中的最大者的函数
{
if(b>a) a=b;
if(c>a) a=c;
return a;
}
double max(double a,double b,double c) //定义求3个双精度数中的最大 者的函数
{
if(b>a) a=b;
if(c>a) a=c;
return a;
}
long max(long a,long b,long c) //定义求3个长整数中的最大者的函 数
{
if(b>a) a=b;
if(c>a) a=c;
return a;
}
- 运行情况如下:
185 -76 567↙ (输入3个整数)
186 i_max=567 (输出3个整数的最大值)
56.87 90.23 -3214.78↙ (输入3个实数)
d_max=90.23 (输出3个双精度数的最大值)
67854 -912456 673456↙ (输入3个长整数)
g_max=673456 (输出3个长整数的最大值)