简体   繁体   English

C++ 函数中的默认值?

[英]C++ Default values in functions?

How exactly do default values in functions work?函数中的默认值究竟是如何工作的? My question pertains to this example:我的问题与这个例子有关:

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?

The compiler gives an error complaining that the argument was NULL and should not be.编译器给出一个错误,抱怨参数为 NULL,不应该是 NULL。 Yet I've defined a default value for it.然而我已经为它定义了一个默认值。

Why is this?为什么是这样?

If a default parameter at position k is supplied, all parameters in positions from k+1 to the end must be supplied as well.如果提供了位置k的默认参数,则还必须提供从k+1到末尾位置的所有参数。 C++ allows you to omit parameters only in the end positions, because otherwise it has no way of matching parameter expressions to formal parameters. C++ 只允许在结束位置省略参数,否则它无法将参数表达式与形式参数匹配。

Consider this example:考虑这个例子:

int func(int a, int b=2, int c, int d=4);
...
foo(10, 20, 30);

This call is ambiguous, because it supplies three parameters out of four.这个调用是模棱两可的,因为它提供了四个参数中的三个。 If declaration above were allowed, C++ would have a choice of calling如果允许上面的声明,C++ 可以选择调用

func(10, 20, 30, 4);

or或者

func(10, 2, 30, 40);

With all defaulted parameters at the end and a rule that parameters are matched by position, there would be no such ambiguity:使用最后的所有默认参数和参数按位置匹配的规则,就不会有这样的歧义:

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

Default arguments are last.默认参数在最后。

int func(int number1, int number2, std::string = "none");
...
func(1,2); 

https://en.wikipedia.org/wiki/Default_argument https://en.wikipedia.org/wiki/Default_argument

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM