定义: 在函数声明或者函数定义的时候直接给形参赋值,这样在函数调用的时候可以不需要再给形参传值,会使用他的默认值。
注意: 参数默认值必须从右向左依次赋值。
#include<bits/stdc++.h>
using namespace std;
void fun0(int t,int a=2,int b=3) // 可以只传前两个值,此时a不再等于默认值,会输出实参的值a=1
{
cout<<a<<' '<<b<<endl;
}
void fun1(int t=2,int a,int b=3) // 报错,默认实参不在形参列表的结尾
{
cout<<a<<' '<<b<<endl;
}
int main()
{
fun0(1,1);
return 0;
}