For the default real parameters of a function, we usually place them in the declaration of the function, but do not specify the default real parameters in the definition: declare the function in the header file: // test. hvoid func (INT I = 0); implement the function in the corresponding source file: // test. cppvoid func (int I) {}// do nothing. If we delete the default real parameter from the Declaration and add it to the definition, or both the Declaration and definition, an error is returned regardless of the value. However, C ++ does not stipulate that this must be the case. c ++ stipulates that the default real parameters of a function can be specified either in the definition or declaration, however, in a file (accurately, it is a scope), the default real parameter can only be specified for one form parameter once. Therefore, we can write as follows:
int func1(int i = -1){return i;}int main(){cout<<func1();}
Here is the default real parameter specified in the definition. We can even write as follows:
int main(){int func1(int i = 1 );cout<<func1();}int func1(int i = -1){return i;}
In the global scope, the specified default value is-1, but in the scope of the main function, the specified default value is 1. Now let's go back to the question we just raised: 1. Why is the default real parameter deleted from the declaration, and an error will be reported when it is added to the definition. Because when the main function (main. CPP) and header file (test. h) When combined, the header file Declaration shows that the func function requires an int type parameter (the Declaration does not indicate that this function has a default parameter), so when compiling main. CPP, the following error occurs: D: \ myprograms \ c ++ \ test \ main. CPP (9 ):
Error c2660: "func": the function does not accept 0 parameters.
2. Why is it added in the declaration and definition? An error is reported. The reason is as mentioned in the book: But in a file (accurately, it is a scope), you can only specify the default real parameter for a form parameter once. When the header file is combined with the source file during compilation, the default parameter is specified multiple times. The Compiler reports the following error: D: \ myprograms \ c ++ \ test. CPP (3 ):
Error c2572: "func": redefinition default parameter: parameter 1
I believe that after reading the above analysis, it is not difficult to understand why the default real parameters are generally placed in the declaration of the function, and the default real parameters are not specified in the definition.