本文介绍了在调用C ++函数时指定默认参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 假设我有这样的代码: void f(int a = 0,int b = 0,int c = 0) { //...Some Code ... } 正如你可以看到上面的代码,参数 a , b 和 c 的默认参数值为0.现在看看我的主要功能如下: int main() { //这里有4种方法调用上面的函数: int a = 2; int b = 3; int c = -1; f(a,b,c); f(a,b); f(a); f(); //注意上面的参数可以改变为其他变量 //。 } 现在我知道我不能跳过一个参数,让它具有默认值,因为该值将计算为该位置的参数。我的意思是,我不能说, f(a,c),因为 c 评估为 b ,这是我不想要的,特别是如果 c 是错误的类型。有没有一种方法调用函数在C ++中指定,在任何给定位置使用任何默认参数值的函数,而不限于从最后一个参数回到无?是否有任何保留关键字来实现这一点,或至少一个解决方法?我可以给出的例子是: f(a,def,c)//其中def将意味着默认值。 解决方案 f(a ,, c)也无效。您可以省略一些最右边的可选参数,但不显示中间的那个。 http://www.learncpp.com/cpp-tutorial/77-default-parameters/ 直接从上面的链接引用: Suppose I have code like this:void f(int a = 0, int b = 0, int c = 0){ //...Some Code...}As you can evidently see above with my code, the parameters a,b, and c have default parameter values of 0. Now take a look at my main function below:int main(){ //Here are 4 ways of calling the above function: int a = 2; int b = 3; int c = -1; f(a, b, c); f(a, b); f(a); f(); //note the above parameters could be changed for the other variables //as well.}Now I know that I can't just skip a parameter, and let it have the default value, because that value would evaluate as the parameter at that position. What I mean is, that I cannot, say call, f(a,c), because, c would be evaluated as b, which is what I don't want, especially if c is the wrong type. Is there a way for the calling function to specify in C++, to use whatever default parameter value there is for the function in any given position, without being limited to going backwards from the last parameter to none? Is there any reserved keyword to achieve this, or at least a work-around? An example I can give would be like:f(a, def, c) //Where def would mean default. 解决方案 There isn't a reserved word for this, and f(a,,c) is not valid either. You can omit a number of rightmost optional parameters, as you show, but not the middle one like that.http://www.learncpp.com/cpp-tutorial/77-default-parameters/Quoting directly from the link above: 这篇关于在调用C ++函数时指定默认参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!