C++ 函数中的默认值?

Joe*_*Bid -1 c++ default-value

函数中的默认值到底是如何工作的?我的问题与这个例子有关:

int func(int number, std::string name = "None", int anotherNumber);

..

int func(int number, std::string name, int anotherNumber){
    ...
}

func(1, 2);
^Error, name is NULL yet we've defined a default value?
Run Code Online (Sandbox Code Playgroud)

编译器给出一个错误,抱怨参数为 NULL 并且不应该为 NULL。但我已经为其定义了默认值。

为什么是这样?

das*_*ght 5

k如果提供了位置处的默认参数,k+1则还必须提供从位置到末尾的所有参数。C++ 只允许在末尾位置省略参数,否则它无法将参数表达式与形式参数相匹配。

考虑这个例子:

int func(int a, int b=2, int c, int d=4);
...
foo(10, 20, 30);
Run Code Online (Sandbox Code Playgroud)

该调用是不明确的,因为它提供了四个参数中的三个。如果允许上述声明,C++ 将可以选择调用

func(10, 20, 30, 4);
Run Code Online (Sandbox Code Playgroud)

或者

func(10, 2, 30, 40);
Run Code Online (Sandbox Code Playgroud)

所有默认参数都放在最后,并且参数按位置匹配的规则,就不会有这样的歧义了:

int func(int a, int b, int c=2, int d=4);
...
foo(10, 20, 30); // means foo(10, 20, 30, 4);
Run Code Online (Sandbox Code Playgroud)