默认参数位于参数列表中间?
我在代码中看到如下所示的函数声明,
void error(char const *msg, bool showKind = true, bool exit);
我首先认为这是一个错误,因为函数中间不能有默认参数,但编译器接受了此声明。有人见过这个吗?我正在使用GCC4.5。这是 GCC 扩展吗?
奇怪的是,如果我把它放在一个单独的文件中并尝试编译,GCC 会拒绝它。我已经仔细检查了所有内容,包括使用的编译器选项。
I saw a function declaration in our code that looked as follows
void error(char const *msg, bool showKind = true, bool exit);
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?
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果在函数的第一个声明中,最后一个参数具有默认值,则该代码将起作用,如下所示:
然后在同一范围内您可以为其他参数提供默认值(从右侧) ),在后面的声明中,如:
可以称为:
Online Demo : http://ideone.com/aFpUn
请注意,如果您提供第一个参数的默认值(从左开始),如果不提供第二个参数的默认值,它将无法编译(按预期): http://ideone .com/5hj46
§8.3.6/4 说,
标准本身的示例:
第二个声明添加了默认值!
另请参阅§8.3.6/6。
That code would work if in the very first declaration of the function, the last parameter has default value, something like this:
And then in the same scope you can provide default values for other arguments (from right side), in the later declaration, as:
which can called as:
Online Demo : http://ideone.com/aFpUn
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 says,
Example from the Standard itself:
The second declaration adds default value!
Also see §8.3.6/6.
答案可能在 8.3.6 中:
8.3.6 默认参数
读完本文后,我发现 MSVC10 在关闭编译器扩展的情况下接受以下内容:
The answer might be in 8.3.6:
8.3.6 Default Arguments
After reading this, I found that MSVC10 accepted the following with compiler extensions turned off: