The default value of C ++ functions problem

If the design function default values, we need to declare the default value from right to left.

#include<iostream>
using namespace std;

int fun(int a,int c,int b=10);

int fun(int a,int c,int b){
    cout<< "a:"<<a<<endl;
    cout<< "b:"<<b<<endl;
    cout<< "c:"<<c<<endl;
}

int  main () {
     fun(10,10);
}
 
Such default value is legitimate, the compiler normally, when the first set of compiler b onto the stack, the value of the function call to use, c = 10 onto the stack, a = 10 placed on the stack.
 
This design approach can be considered from the perspective of the caller.
Assume function declaration written like this:
int fun(int a,int b=10,int c);
这样声明似乎合乎情理,实际上,在调用的时候,如果希望b使用默认值,a和c使用我调用函数给的值,没有办法调用。
实际中,这样写编译不通过。
遇到这种情况,就需要把含默认值的变量放在最右边,把没有默认值的变量放在左边。
int fun(int a,int c,int b=10);
 
这样声明之后,就可以这样调用函数了
fun(10,10);

Guess you like

Origin www.cnblogs.com/truthfountain/p/11527461.html