内联函数和前向引用

inline functions and forward references

https://www.studytonight.com/cpp/inline-functions.php 他们正在解释内联函数

所有内联函数都由编译器在 class 声明结束时计算。

class ForwardReference
{
    int i;
    public:
    // call to undeclared function
    int f() 
    {
        return g()+10;
    }
    int g() 
    {
        return i;
    }
};

int main()
{
    ForwardReference fr;
    fr.f();
}

最后他们说: "You must be thinking that this will lead to compile time error, but in this case it will work, because no inline function in a class is evaluated until the closing braces of class declaration."

......

为什么会出现编译时错误?是因为没有设置 i 的值吗?如果是这样,有人能更好地解释它为什么有效吗,我不明白这里的重点是什么,如果成员函数是内联的或不是内联的,它的工作方式是否相同?

他们在这里暗示的是,尽管 g 写成 below/after,f,但 f 可以仍然引用它没有错误。

如果您将它们移出 class 并同时定义+声明它们,那么您会看到编译错误(因为 f 看不到任何 g ).

int f(){
    return g() + 10;
}

int g(){
    return 32;
}

int main(){
    return f();
}

自己看on compiler explorer.

书上明确指出给你"no inline function in a class is evaluated until the closing braces of class declaration"。在 class 声明之外,使用普通函数,这会失败:

int f() 
{
    return g()+10;
}
int g()
{
    return 0;
}

尝试编译仅包含此内容的 C++ 源文件,然后您自己看看。

在 C++ 中,所有函数都必须在使用前声明。由于 g() 没有声明,这是错误的,你的编译器会拒绝它。 g() 必须在引用前声明:

int g();

int f() 
{
    return g()+10;
}
int g()
{
    return 0;
}

这不适用于内联 class 方法,因为正如您的书所解释的那样,它们在 class 声明完成时得到有效评估。此时 f()g() 方法都被声明,并且从 f()g() 的引用是格式正确的。