Where does C++ specify default parameters

In the example in the previous section, we specified default parameters at the function definition. In addition to function definitions, you can also specify default parameters at function declarations. However, the situation becomes a little more complicated when there is a function declaration. Sometimes you can specify default parameters at both the declaration and definition, and sometimes you can only specify at the declaration. Please see the following example (Example 1):

#include <iostream>
using namespace std;
void func(int a, int b = 10, int c = 36);
int main(){
    func(99);
    return 0;
}
void func(int a, int b = 10, int c = 36){
    cout<<a<<", "<<b<<", "<<c<<endl;
}

This code will report an error when compiling, and the error message indicates that default parameters cannot be specified in both the function definition and function declaration. Make a slight modification to the code to place the definition of the func() function in a different source file, as shown below (Example 2).

main.cpp code:

#include <iostream>
using namespace std;
void func(int a, int b = 10, int c = 36);
int main(){
    func(99);
    return 0;
}

おすすめ

転載: blog.csdn.net/m0_68539124/article/details/129330406