默认参数
语法: 返回值类型 函数名 (参数 = 默认值){}
如下
#include <iostream>
using namespace std;
int test(int a, int b = 10){
return a+b;
}
int main() {
int c = test(10);// a为10, b默认值10
cout << c << endl ;
return 0;
}
注意1: 有默认值的位置往右都要有默认值,不然报错
#include <iostream>
using namespace std;
int test(int a, int b = 10, int c){ //会报错,b后面的形参都需要默认值
return a+b+c;
}
int main() {
int c = test(10);
cout << c << endl ;
return 0;
}
注意2:如果在函数声明中形参有默认参数,函数实现就不能有默认参数(两者只能取其一)
#include <iostream>
using namespace std;
int test(int a, int b = 10);
int main() {
int c = test(10);
cout << c << endl ;
return 0;
}
int test(int a, int b = 20){//会报错重复,默认为10也同理
return a+b;
}
函数占位参数
语法: 返回值类型 函数名 (数字类型){}
如下:
#include <iostream>
using namespace std;
void test(int a, int){
cout << "test()" << endl;
}
int main() {
test(10,10);
return 0;
}
占位参数也可以设默认值
#include <iostream>
using namespace std;
void test(int a, int = 10){//
cout << "test()" << endl;
}
int main() {
test(10);
return 0;
}