C ++搞砸了:可选参数强制为强制性

C ++搞砸了:可选参数强制为强制性

问题描述:

我想要一个带有可选参数的函数.但是,VC ++引发了我无法理解的错误.代码很简单,如下所示:

I want to have a function with optional argument. However, VC++ is throwing an error I cannot comprehend. The code is as simple as follows:

#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()之前,则不会出错.到底是怎么回事?请帮忙.谢谢.

However if I move myFunction() before main(), it gives no error. What is going on? Please help. Thank you.

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

This error is because you have optional variables when you call your function, but not in your declaration.

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

This will create a function with two variables:

void myFunction(string something, int w);

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

However, this would make the second variable optional:

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

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

You need to make the declaration have a optional variable.

此外,令您惊讶的是,您的编译器没有尝试吐出与重新定义有关的某种错误. (甚至可能是编译器错误!我将对此进行最新研究. 更新:似乎不是编译器错误,但绝对是我很想拥有的功能.即使是错误,也可能与 linker 相关.)

Also, I am surprised your compiler didn't try to spit some sort of error relating to a redefinition. (That might even be a compiler bug! I will update on research into this. Update: Doesn't seem like compiler bug, but definitely a feature I would love to have. Even if it was a bug, it would be linker related.)