参数列表中间的默认参数? [英] Default argument in the middle of parameter list?

查看:157
本文介绍了参数列表中间的默认参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我们的代码中看到一个函数声明如下:

I saw a function declaration in our code that looked as follows

void error(char const *msg, bool showKind = true, bool exit);

我认为这是一个错误,因为你不能在函数中间有默认参数,编译器接受此声明。有没有人看到这个?我使用GCC4.5。这是一个GCC扩展吗?

I thought first that this is an error because you cannot have default arguments in the middle of functions, but the compiler accepted this declaration. Has anyone seen this before? I'm using GCC4.5. Is this a GCC extension?

奇怪的是,如果我把这个在一个单独的文件,并尝试编译,GCC拒绝。我已经双重检查了一切,包括使用的编译器选项。

The weird thing is, if I take this out in a separate file and try to compile, GCC rejects it. I've double checked everything, including the compiler options used.

推荐答案

如果在函数的第一个声明中,最后一个参数有默认值,

That code would work if in the very first declaration of the function, the last parameter has default value, something like this:

//declaration
void error(char const *msg, bool showKind, bool exit = false);

然后在同一范围内 您可以为其他参数提供默认值(从右侧),在后面的声明中,如下:

And then in the same scope you can provide default values for other arguments (from right side), in the later declaration, as:

void error(char const *msg, bool showKind = true, bool exit); //okay

//void error(char const *msg = 0 , bool showKind, bool exit); // error

可以调用:

error("some error messsage");
error("some error messsage", false);
error("some error messsage", false, true);

在线演示: http: //ideone.com/aFpUn

请注意,如果您为第一个参数提供默认值(从左开始),而不为第二个参数提供默认值无法编译(如预期): http://ideone.com/5hj46

Note if you provide default value for the first parameter (from left), without providing default value for the second, it wouldn't compile (as expected) : http://ideone.com/5hj46

§8.3.6/ 4说,

§8.3.6/4 says,


对于非模板函数,默认
参数可以在同一个
范围内的函数的后续
声明中添加。

For non-template functions, default arguments can be added in later declarations of a function in the same scope.

标准本身的示例:

void f(int, int);
void f(int, int = 7);

第二个声明添加了默认值!

The second declaration adds default value!

另见§8.3.6/ 6。

Also see §8.3.6/6.

这篇关于参数列表中间的默认参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆