简体   繁体   English

初始化参数时会发生什么? C ++

[英]What happens when you initialize a parameter? C++

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

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

k will output 2. My question is, in what order does foo initialize the parameter and acquire the argument? k将输出2.我的问题是,foo以什么顺序初始化参数并获取参数? What is the process foo goes through to get 2. Thank you 什么是foo经历的过程2.谢谢

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

This prototype means that if you call foo with only the first param the second is implicitly set to 7. 这个原型意味着如果你只用第一个参数调用foo,那么第二个被隐式设置为7。

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

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 (ie foo(5) ). 每当调用foo时缺少参数k,编译器会自动插入值为7(即foo(5) )。 If it is not missing, the actual parameter is taken (ie foo(1, 2) ). 如果没有丢失,则采用实际参数(即foo(1, 2) )。

Your example is no different than if you had declared foo without the default parameter. 您的示例与没有使用默认参数声明foo的情况没有什么不同。

Default parameters are handled by the compiler. 默认参数由编译器处理。 When the compiler encounters a call to foo with only one parameter, it will add the second parameter for you. 当编译器遇到只有一个参数的foo调用时,它会为你添加第二个参数。

For example: 例如:

foo(3);

will get transformed by the compiler to 将被编译器转换为

foo(3, 7);

That's all. 就这样。

This is called function initializer. 这称为函数初始化器。

If you don't assign the second parameter as foo(1,2) , it'll output "7" on the screen (when you use foo(1) ). 如果不将第二个参数指定为foo(1,2),它将在屏幕上输出“7”(当您使用foo(1)时)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM