我在我们的代码中看到了如下所示的函数声明
void error(char const *msg, bool showKind = true, bool exit);
我首先认为这是一个错误,因为函数中间不能有默认参数,但编译器接受了这个声明。有没有人见过这个?我正在使用 GCC4.5。这是 GCC 扩展吗?
奇怪的是,如果我把它放在一个单独的文件中并尝试编译,GCC 会拒绝它。我已经仔细检查了所有内容,包括使用的编译器选项。
最佳答案
如果在函数的第一个声明中,最后一个参数具有默认值,则该代码将起作用,如下所示:
//declaration
void error(char const *msg, bool showKind, bool exit = false);
然后在同一范围内你可以在后面的声明中为其他参数(从右侧)提供默认值,如:
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/5hj46
§8.3.6/4 说,
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);
第二个声明添加默认值!
另见 §8.3.6/6。
关于c++ - 参数列表中间的默认参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5637679/