从同一文件中定义的类访问外部函数

Cem*_*mre 0 c++ class function

如果我有一个类定义

class myClass
{
  void x(); 
};


void myClass::x()
{
   hello(); // error: ‘hello’ was not declared in this scope
}

void hello()
{
   cout << "Hello\n" << endl;
}
Run Code Online (Sandbox Code Playgroud)

如何调用在类范围之外定义并位于同一文件中的函数?我知道我可以使用,Namespace::function但我不确定在这种情况下我应该使用什么Namespace

Luc*_*ore 5

在使用之前,您必须至少声明它(如果没有定义它).

通常,如果函数的功能仅用于该转换单元,则在匿名命名空间中完成:

class myClass
{
  void x(); 
};

namespace
{
   void hello()
   {
      cout << "Hello\n" << endl;
   }
}

void myClass::x()
{
   hello(); // error: ‘hello’ was not declared in this scope
}
Run Code Online (Sandbox Code Playgroud)

这给了函数内部链接(类似于声明它static)并且仅在该TU中可用.