The C++ default parameters are like a spare tire for the function parameters
Default parameter concept
The default parameter is a default value specified for the parameter of the function when declaring or defining the function. When calling this function, if the actual parameter is not specified, the default value is used, otherwise the specified actual parameter is used.
It can be explained clearly with the following piece of code:
void TestFunc(int a = 0)
{
cout<<a<<endl;
}
int mian()
{
TestFunc();//没有传参时,使用参数的默认值,即a=0
TestFunc(10);//传参时,使用指定的实参
}
Default parameter classification
1. All default parameters
void TestFunc(int a = 0,int b = 1,int c = 2)
{
cout<<a<<endl;
cout<<b<<endl;
cout<<c<<endl;
}
2. Semi-default parameters
void TestFunc(int a,int b = 1,int c = 2)
{
cout<<a<<endl;
cout<<b<<endl;
cout<<c<<endl;
}
Places that need special attention:
- When using semi-default parameters, they must be given in order from right to left, and cannot be given at intervals
- The default parameters cannot appear in the function declaration and definition at the same time, because they appear in two places at the same time, and it happens that the values provided in the two positions are different, and the compiler cannot determine which default value to use
- The default value must be a constant or a global variable
- C language compiler does not support default parameters