缺省参数
缺省参数是声明或定义函数时为函数的参数指定一个默认值。在调用该函数时,如果没有指定实参则采用该默认值,否则使用指定的实参。
例
void TestFunc(int a = 0){
cout<<a<<endl;
}
int main(){
TestFunc(); // 没有传参时,使用参数的默认值
TestFunc(10); // 传参时,使用指定的实参
}
缺省参数分类
1.全缺省参数
void TestFunc(int a = 10, int b = 20, int c = 30){
cout<<"a = "<<a<<endl;
cout<<"b = "<<b<<endl;
cout<<"c = "<<c<<endl;
}
2.半缺省参数
注意:半缺省,需要保证函数参数默认值从右向左依次给出,中间不能有空隔
void TestFunc(int a, int b = 10, int c = 20){
cout<<"a = "<<a<<endl;
cout<<"b = "<<b<<endl;
cout<<"c = "<<c<<endl;
}
注意:缺省参数不能在函数声明和定义中同时出现
函数重载
C++允许在同一作用域中声明几个功能类似的同名函数,这些同名函数的
形参列表(参数个数 或 类型 或 顺序)必须不同,常用来处理实现功能类似数据类型不同的问题
例如
int Add(int a, int b){
return a + b;
}
double Add(double a, double b){
return a + b;
}
int Add(char a, int b){
return a + b;
}
int Add(int a, int b, int c){
return a + b + c;
}