参数个数不同的函数载体(C++)

来源:互联网 发布:桐乡淘宝摄影基地 编辑:程序博客网 时间:2024/05/01 18:13
/*参数个数不同的函数重载是指,
具有不同参数个数的函数可以使用同一个函数名,

编译器在调用该函数的根据实际参数的个数判断应该调用*/ 


#include <iostream>
using namespace std;
int max(int a,int b);/*声明带有2个参数的函数max()*/
int max(int a,int b,int c);/*声明带有3个参数的函数max()*/
int max(int a,int b,int c,int d);/*声明带有4个参数的函数max()*/


int main()
{
int result;
cout<<"请输入2个整数:"<<endl;
int a,b;
cin>>a>>b;
result=max(a,b);
cout<<"2个整数的最大值:"<<result<<endl;
cout<<endl;
cout<<"请输入3个整数:"<<endl;
int i,j,k;
cin>>i>>j>>k;
result=max(i,j,k);
cout<<"3个整数的最大值:"<<result<<endl;
cout<<endl;
cout<<"请输入4个整数:"<<endl;
int v,x,y,z;
result=max(v,x,y,z);
cout<<"4个整数的最大值:"<<result<<endl;
cout<<endl;
return 0; 



int max(int a,int b)                 /*2个*/
{
return a>b?a:b;
}


int max(int a,int b,int c)                  /*3个*/
{
int t=max(a,b);
return max(t,c);
}


int max(int a,int b,int c,int d)     /*定义一个带有4个参数的函数max()*/
{
int t1=max(a,b);
int t2=max(c,d);                /*调用函数*/ 
return max(t1,t2);             /*返回调用函数*/

}


0 0
原创粉丝点击