c++ - 参数列表中间的默认参数?

标签 c++ default-arguments

我在我们的代码中看到了如下所示的函数声明

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/aFpUn

请注意,如果您为第一个参数(左起)提供默认值,而没有为第二个参数提供默认值,它将无法编译(如预期的那样):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/

相关文章:

c++ - char* 到 number 的值

c++ - 将一张 map 复制到另一张 map

c++ - QTableWidget 中的 SelectedRows 列表

c++ - 使用默认参数从 lambda 调用最少数量的参数

c - 在 C 中,我们如何强制可变参数函数中的最后一个参数为终止空值?

C++静态模板类成员作为友元模板函数默认参数

c++ - pthreads : What are the different models of pthread implemenation

c++ - 如何从终端读取 .txt 文件,然后从文件中提取内容?

javascript - 数组作为默认参数在 Javascript 中安全吗?

c++ - 为什么允许这些默认参数?