详解C++中的内联函数和函数重载

2020-01-06 13:49:36王振洲

C++允许用同一函数名定义多个函数,这些函数的参数个数和参数类型不同。这就是函数的重载(function overloading)。即对一个函数名重新赋予它新的含义,使一个函数名可以多用。

对上面求最大数的问题可以编写如下的C++程序。

【例】求3个数中最大的数(分别考虑整数、双精度数、长整数的情况)。

 

 
  1. #include <iostream>  using namespace std; 
  2. int main( )  { 
  3. int max(int a,int b,int c); //函数声明  double max(double a,double b,double c); //函数声明 
  4. long max(long a,long b,long c);//函数声明  int i1,i2,i3,i; 
  5. cin>>i1>>i2>>i3; //输入3个整数  i=max(i1,i2,i3); //求3个整数中的最大者 
  6. cout<<"i_max="<<i<<endl;  double d1,d2,d3,d; 
  7. cin>>d1>>d2>>d3; //输入3个双精度数  d=max(d1,d2,d3); //求3个双精度数中的最大者 
  8. cout<<"d_max="<<d<<endl;  long g1,g2,g3,g; 
  9. cin>>g1>>g2>>g3; //输入3个长整数  g=max(g1,g2,g3); //求3个长整数中的最大者 
  10. cout<<"g_max="<<g<<endl;  } 
  11. int max(int a,int b,int c) //定义求3个整数中的最大者的函数  { 
  12. if(b>a) a=b;  if(c>a) a=c; 
  13. return a;  } 
  14. double max(double a,double b,double c)//定义求3个双精度数中的最大者的函数  { 
  15. if(b>a) a=b;  if(c>a) a=c; 
  16. return a;  } 
  17. long max(long a,long b,long c) //定义求3个长整数中的最大者的函数  { 
  18. if(b>a) a=b;  if(c>a) a=c; 
  19. return a;  }