c++ - 在指定其他参数时使用前导参数的默认值

标签 c++ function parameters

我想知道如何跳过覆盖 C++ 函数中的参数。例如,看下面的函数,如果 output 有 1 个参数,你可以直接调用它而不发送任何参数,比如 output();

这将输出 5,因为 xor 的默认值为 5。但是,如果我想覆盖“vor”,并将 xor 保留为其默认值,我该怎么做?

输出(NULL, 20);

上面没有工作,它只是将 xor 初始化为 0。

void output(int xor = 5, int vor = 15) {
    cout << xor << " " << vor << endl;
}

int main()
{
    output(10, 20);
}

最佳答案

如果你想覆盖第二个默认参数,那么你必须指定第一个参数。

函数的可能调用如下

output();         // corresponds to output( 5, 15 );
output( x );      // corresponds to output( x, 15 );
output( x, y );   // corresponds to output( x, y );

其中 x 和 y 是一些任意参数。

关于c++ - 在指定其他参数时使用前导参数的默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25463607/

相关文章:

c++ - 为什么 C 编译器会丢弃我的 &0xFF 掩码?

c++ - 使用输出迭代器的通用函数示例不起作用

c++ - Infile 不完整类型错误

vba - VBA 中的 WorksheetFunction.IsNumber() 和 IsNumeric() 有什么区别?

javascript - 使用 Javascript 将 URL 参数传递给 href 链接

c++ - 如何移动 QGraphicsView 中的 QWidget?

c++ - 在笛卡尔平面上旋转 X、Y 坐标的问题

javascript - 在 JavaScript 中恢复无效函数

具有默认参数的Objective-C函数?

c - C 中的空参数