初始化参数会怎样? C ++ [英] What happens when you initialize a parameter? C++

查看:73
本文介绍了初始化参数会怎样? C ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

void foo (int i , int k = 7) {
    cout << k;
}

int main(){
    foo(1, 2);    
}

k将输出2. 我的问题是,foo以什么顺序初始化参数并获取参数? foo获得2的过程是什么?谢谢

k will output 2. My question is, in what order does foo initialize the parameter and acquire the argument? What is the process foo goes through to get 2. Thank you

推荐答案

 void foo (int i , int k = 7);

此原型意味着,如果仅使用第一个参数调用foo,则第二个参数将隐式设置为7.

This prototype means that if you call foo with only the first param the second is implicitly set to 7.

    foo(1, 2);  // i=1, k=2
    foo(5);  // <==> foo(5, 7)   i=1, k=7

此机制在编译时由编译器解决.每当在缺少参数k的情况下调用foo时,编译器都会自动将其插入值为7(即foo(5)).如果没有缺失,则采用实际参数(即foo(1, 2)).

This mechanism is resolved at compile time, by the compiler. Whenever foo is called with the param k missing, the compiler automatically inserts it with the value 7 (i.e. foo(5)). If it is not missing, the actual parameter is taken (i.e. foo(1, 2)).

这篇关于初始化参数会怎样? C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆