为什么一个函数声明在另一个函数中编译,它做什么

Why does a function declaration within another function compile and what does it do?

本文关键字:函数 编译 什么 另一个 声明 为什么 一个      更新时间:2023-10-16

我打算调用私有类成员函数,但由于copy&paste错误,粘贴了头文件中声明该函数的行:

void DebugView::on_cbYAxisEnabled_stateChanged(int)
{
    void updateAxisEnabled();
}
不是

void DebugView::on_cbYAxisEnabled_stateChanged(int)
{
    updateAxisEnabled();
}

令人惊讶的是,代码被编译并执行。但是方法updateAxisEnabled()没有被执行。

那么,为什么它可以编译呢?这里是一个局部函数声明在一个方法体或有void指示编译器忽略之后?

编译器为Visual Studio 2008。

注::我知道函数中的类声明/定义,但不知道c++中函数中的函数。

void updateAxisEnabled();是一个函数声明

示例:

#include <cstdio>
void a();
void b();
int main(void) {
    a();
    b();
    return 0;
}
void a() {
    void c(); // Declaration
    c(); // Call it
}
void b() {
    c(); // Error: not declared
}
void c() {
    puts("Hello, world!");
}

完全允许在函数作用域中声明函数:函数可以在任何作用域中声明。

c++程序员的一个常见错误确实是:
void foo()
{
    MyObject bar(); // 1
    bar.someMethod(); // 2
}

这将悲惨地编译失败,因为第1行是而不是声明名为barMyObject并显式调用其构造函数;相反,它声明了一个名为bar函数,返回一个MyObject。因此,确实没有对象可以调用someMethod