【发布时间】:2015-04-12 18:37:31
【问题描述】:
不久前我正在浏览C++11 standard draft 并遇到了这个(在第 8.3.6 节,第 204 页):
void g(int = 0, ...); // OK, ellipsis is not a parameter so it can follow
// a parameter with a default argument
void f(int, int);
void f(int, int = 7);
void h() {
f(3); // OK, calls f(3, 7)
void f(int = 1, int); // error: does not use default
// from surrounding scope
}
void m() {
void f(int, int); // has no defaults
f(4); // error: wrong number of arguments
void f(int, int = 5); // OK
f(4); // OK, calls f(4, 5);
void f(int, int = 5); // error: cannot redefine, even to
// same value
}
void n() {
f(6); // OK, calls f(6, 7)
}
这与函数的默认参数有关。令我印象深刻的是函数声明出现在函数范围内。这是为什么?这个功能是做什么用的?
【问题讨论】:
-
我用它来声明一个我知道只会在作用域内调用的函数。
-
简短的回答是它很少被使用。从理论上讲,如果(例如)你有一个同名的变量和函数,它可能会很有用。内部范围的声明将隐藏外部范围的声明。
-
stackoverflow.com/a/35007616/785194 是快速答案(对于 C)。
标签: c++ function scope declaration