相关疑难解决方法(0)

调用C++函数时指定默认参数

假设我有这样的代码:

void f(int a = 0, int b = 0, int c = 0)
{
    //...Some Code...
}
Run Code Online (Sandbox Code Playgroud)

正如您可以在上面看到我的代码,参数a,b以及c默认参数值为0.现在看看我的主要功能如下:

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.
}
Run Code Online (Sandbox Code Playgroud)

现在我知道我不能只跳过一个参数,并让它具有默认值,因为该值将作为该位置的参数进行评估.我的意思是,我不能,比如说f(a,c),因为,c将被评估为b,这是我不想要的,特别是如果c是错误的类型.有没有一种方法让调用函数在C++中指定,在任何给定的位置使用函数的任何默认参数值,而不限于从最后一个参数向后转到无?是否有任何保留关键字来实现这一目标,或者至少是解决方法?我可以给出一个例子:

f(a, …
Run Code Online (Sandbox Code Playgroud)

c++ language-construct default-value c++11

14
推荐指数
3
解决办法
4561
查看次数

标签 统计

c++ ×1

c++11 ×1

default-value ×1

language-construct ×1