C++函数的默认值问题

函数如果设计了默认值,需要从右向左声明默认值。

#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);
}
 
这样使用默认值是合法的,编译正常,当编译器进行编译时先将b放入堆栈,在使用调用函数的值,c=10放入堆栈,a=10放入堆栈。
 
这样的设计方法,可以从调用者的角度考虑。
假设函数的声明写成这样:
int fun(int a,int b=10,int c);
这样声明似乎合乎情理,实际上,在调用的时候,如果希望b使用默认值,a和c使用我调用函数给的值,没有办法调用。
实际中,这样写编译不通过。
遇到这种情况,就需要把含默认值的变量放在最右边,把没有默认值的变量放在左边。
int fun(int a,int c,int b=10);
 
这样声明之后,就可以这样调用函数了
fun(10,10);

猜你喜欢

转载自www.cnblogs.com/truthfountain/p/11527461.html