How to use:
(1) When a function is declared or defined, the parameter is assigned a value directly, which is the default parameter.
(2) When a function is called, omit some or all of the arguments, and the default arguments are used instead.
Note:
(1) The general declaration function is to set the default parameter.
If the default parameters are set when the function is declared and defined, the default arguments for the function declaration prevail.
Copy Code code as follows:
#include <iostream>
using namespace Std;
int main ()
{
Double Add (double a=3.2,double b=9.6);//set default parameter when function declaration
Cout<<add () <<endl; Use default parameters
return 0;
}
Double Add (double a=3.2,double b=9.5)//Set default parameters when defining functions
{
return a+b;
}
Run Result:
(2) The default parameters are defined in order from right to left.
That is, if you set a default value, the parameters to the right of the parameter should also be set to a default value.
That
Copy Code code as follows:
<pre name= "code" class= "CPP" >int Add (Int. a,int b=1,int c=1);</pre>
This is the right thing to do.
and
Copy Code code as follows:
int add (int a=1,int b,int c);
It is wrong to do so.
This is done because after the arguments are passed to the system, the system matches the parameters from left to right.
If the function is add (1,2), then how much is a=1,b=2,c equal to? We can only get the value of C when we pass all the parameters in the past, but why do we have to set the default parameters for the function?
So the compiler does not allow programmers to do this because it makes no sense to do so.
(3) The order in which the default parameters are called is from left to right.
When we use a function, the argument must be written from left to right.
Copy Code code as follows:
/* Correct usage * *
Add (1,2,3);//Pass the value of three parameters
Add (1,2);//Pass the value of two parameters
Add (1);//Pass the value of a parameter
Add ();//Do not pass the value of the parameter
/* Wrong usage * *
Add (, 2, 3);//Can not omit the value of the left parameter, should be left to right and right to the value
Bad tip: