C++ 缺少默认参数 - 编译器错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5740296/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 18:47:01  来源:igfitidea点击:

Missing default argument - compiler error

c++g++default-arguments

提问by cnicutar

void func ( string word = "hello", int b ) {

  // some jobs

}

in another function

 //calling 
 func ( "", 10 ) ;

When I have compiled it, compiler emits error ;

当我编译它时,编译器发出错误;

default argument missing for parameter 

Howcan I fix it without changing anything, of course, such as not making "int b = 0" ? Moreover, I want use that function like func ( 10 ) or func ( "hi" ) ? Is my compiler not do its job, properly ?

我怎样才能在不改变任何东西的情况下修复它,当然,比如不制作 "int b = 0" ?此外,我想使用像 func ( 10 ) 或 func ( "hi" ) 这样的函数? 我的编译器没有正确地完成它的工作吗?

回答by cnicutar

You can't have non-default parameters afteryour default parameters begin. Put another way, how would you specify a value for bleaving wordto the default of "hello" ?

默认参数开始不能有非默认参数。换句话说,您将如何指定一个值以b保留word默认值 "hello" ?

回答by Chris

The arguments with a default value have to come in the end of the argument list.

具有默认值的参数必须出现在参数列表的末尾。

So just change your function declaration to

所以只需将您的函数声明更改为

void func(int b, string word = "hello")

回答by Mike Seymour

Parameters with default values have to come at the end of the list because, when calling the function, you can leave arguments off the end, but can't miss them out in the middle.

具有默认值的参数必须放在列表的末尾,因为在调用函数时,您可以将参数放在末尾,但不能在中间遗漏它们。

Since your arguments have different types, you can get the same effect using an overload:

由于您的参数具有不同的类型,您可以使用重载获得相同的效果:

void func ( string word, int b ) {

  // some jobs

}

void func ( int b ) { func("hello", b); }

回答by iammilind

The error message is proper. If the default argument is assigned to a given parameter then all subsequent parameters should have a default argument. You can fix it in 2 ways;

错误信息是正确的。如果将默认参数分配给给定参数,则所有后续参数都应具有默认参数。您可以通过两种方式修复它;

(1) change the order of the argument:

(1) 改变参数的顺序:

void func (int b, string word = "hello");

(2) Assign a default value to b:

(2) 为 分配一个默认值b

void func (string word = "hello", int b = 0);

回答by anatolyg

You cannot fix it without changing anything!

你不能在不改变任何东西的情况下修复它!

To fix it, you can use overloading:

要修复它,您可以使用重载:

void func ( string word, int b ) {
  // some jobs
}

void func ( string word ) {
    func( word, 999 );
}

void func ( int b ) {
    func( "hello", b );
}