Hen*_*ela 6 c++ scope declaration function
我前段时间正在阅读C++ 11标准草案并遇到过这个草案(见§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)
}
Run Code Online (Sandbox Code Playgroud)
这与函数的默认参数有关.令我感到震惊的是函数声明出现在函数范围内.这是为什么?这个功能用于什么?
虽然我不知道你可以做到这一点,但我测试了它并且它有效.我想你可以用它来转发声明后面定义的函数,如下所示:
#include <iostream>
void f()
{
void g(); // forward declaration
g();
}
void g()
{
std::cout << "Hurray!" << std::endl;
}
int main()
{
f();
}
Run Code Online (Sandbox Code Playgroud)
如果删除前向声明,程序将无法编译.因此,通过这种方式,您可以获得某种基于范围的前向声明可见性.