在其声明之上调用函数

fre*_*low 6 c++ scope namespaces class forward-declaration

void foo()
{
    bar();          // error: ‘bar’ has not been declared
}

void bar()
{
}

namespace N
{
    void foo()
    {
        N::bar();   // error: ‘bar’ is not a member of ‘N’
    }

    void bar()
    {
    }
}

class C
{
    static void foo()
    {
        C::bar();   // works just fine
    }

    static void bar()
    {
    }
};
Run Code Online (Sandbox Code Playgroud)

处理对声明之外的函数调用的这种不一致背后的理由是什么?为什么我可以在一个类中完成它,但不能在命名空间内或全局范围内?

Bo *_*son 3

您可以在类内部定义成员函数,也可以在类声明之后定义成员函数,或者分别定义其中的一些成员函数。

为了在这里获得一些一致性,具有内联定义函数的类的规则是它仍然必须被编译,就好像函数是在类之后定义的一样。

你的代码

class C {
     static void foo()
     {
         C::bar();   // works just fine 
     }

     static void bar()
     {     }
 }; 
Run Code Online (Sandbox Code Playgroud)

编译结果与

class C {
     static void foo();
     static void bar();
 }; 

 void C::foo()
 {  C::bar();  }

 void C::bar()
 {     }
Run Code Online (Sandbox Code Playgroud)

现在可见性不再有什么神奇之处,因为函数都可以看到类中声明的所有内容。