与 python 中的默认参数类似,C++ 中同样支持默认参数。
默认参数是给形式参数加上默认值。如果调用函数时传入了对应的实参,就使用实参的值替换默认值,如果没有传入实参,形参则使用默认值。
注意事项:
1)如果某个形参数有默认值,那么从这个位置开始,后面所有的形参都必须有默认值
2)默认参数只能从右往左添加默认值
3)默认参数应该放到函数原型中,而不是函数定义中
占位参数:在函数形参中,只写数据类型,不写参数名,起到占位作用(运算符重载时使用)
#include <iostream>
#include <cstring>
using namespace std;
int GetSum(int a, int b = 5){
return a + b;
}
// 注意在函数声明中使用默认参数,而不是函数定义中使用
int Add(int a, int b = 10);
// 占位参数,只写数据类型,不写参数名
void fun(int a, int){
puts("hello");
}
int main(){
cout << "GetSum(10, 20): " << GetSum(10, 20) << endl; // 30
cout << "GetSum(10): " << GetSum(10) << endl; // 15
cout << "Add(1, 2): " << Add(1, 2) << endl; // 3
cout << "Add(1): " << Add(1) << endl; // 11
// fun(1); 这样是报错的,必须传入两个参数
fun(1, 2); // 输出 "hello"
return 0;
}
int Add(int c, int d){
return c + d;
}