C++-函数范围内的函数声明

C++ - Function declarations inside function scopes?

本文关键字:函数 声明 范围内 C++-      更新时间:2023-10-16

不久前,我正在浏览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)
}

这与函数的默认参数有关。令我印象深刻的是,函数声明出现在函数范围中。为什么?此功能的用途是什么?

虽然我不知道你能做到这一点,但我测试了它,它能工作。我想您可以使用它来转发稍后定义的声明函数,如下所示:

#include <iostream>
void f()
{
    void g(); // forward declaration
    g();
}
void g()
{
    std::cout << "Hurray!" << std::endl;
}
int main()
{
    f();
}

如果删除正向声明,程序将不会编译。因此,通过这种方式,您可以获得某种基于范围的前向声明可见性。

任何函数/变量声明都有其可见性和作用域。例如,如果在类中,则只有类成员才能看到它。如果在函数中,则在我们声明变量或函数之后,只有函数才能对它具有可见性。

我们通常在函数范围内使用数据结构。但编译器的语法规则适用于两者,因为函数本身有地址,因此可见性也适用于它。