C++ 搞砸了 : optional argument forced to be mandatory

标签 c++ optional-arguments

我想要一个带有可选参数的函数。但是,VC++ 抛出一个我无法理解的错误。代码简单如下:

#include <iostream>
#include <iomanip>
#include <string>
using namespace std;

void myFunction(string something, int w);

int main()
{
    myFunction("a string");

    int a = 1;
}

void myFunction(string something, int w = 5)
{
    cout << something << " - " << w << endl;
}

它提示:

'myFunction': function does not take 1 arguments

然而,如果我将 myFunction() 移动到 main() 之前,它不会给出错误。到底是怎么回事?请帮忙。谢谢。

最佳答案

此错误是因为您在调用函数时有可选变量,但在声明中没有。

这将创建一个具有两个变量的函数:

void myFunction(string something, int w);

但是,这会使第二个变量成为可选的:

void myFunction(string something, int w=5);

您需要使声明具有可选变量。

此外,令我惊讶的是您的编译器没有尝试吐出与重新定义相关的某种错误。 (这甚至可能是一个编译器错误!我将更新对此的研究。 更新: 看起来不像是编译器错误,但绝对是我希望拥有的功能. 即使它是一个错误,它也会与链接器相关。)

关于C++ 搞砸了 : optional argument forced to be mandatory,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49204971/

相关文章:

c++ - UTF8 字符到十六进制值字符串

c++ - 根据模板参数删除成员

recursion - 如何在 CHICKEN 中实现可选参数?

c# - 为什么 C# 允许通过可选参数进行不明确的函数调用?

inheritance - 传播可选参数

c++ - 初始化从 QMainWindow 类到 QDialog 类的 Ui 指针

c++ - 将 std::vector 作为模板模板参数传递时出错 - 在 GCC 中有效,在 MSVC 中失败

c++ - make_pair 命名空间污染

r - mapply 的 MoreArgs 参数什么时候不能被 R 的向量回收规则替换?

matlab - 如何将 MATLAB 的 inputParser 与可选字符串输入一起使用?文档说 "use a validation function"但不清楚如何做到这一点