0

クラス定義がある場合

class myClass
{
  void x(); 
};


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

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

クラスのスコープ外で定義され、同じファイルにある関数を呼び出すにはどうすればよいですか? 使用できることはわかっていますNamespace::functionが、この場合は何に使用すればよいかわかりませんNamespace

4

2 に答える 2

5

使用する前に、少なくとも宣言する必要があります (定義しない場合)。

通常、関数の機能がその翻訳単位でのみ使用される場合、これは匿名の名前空間で行われます。

class myClass
{
  void x(); 
};

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

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

これにより、関数に内部リンケージが与えられ (宣言するのと同様static)、その TU でのみ使用できます。

于 2012-07-09T22:44:48.167 に答える
4

関数が使用されている場所の前(メソッドの前hello) にファイル内で関数を定義する、関数が使用されている場所の前に関数プロトタイプを提供します。x

void hello();  // function definition is later in the file

void myClass::x()
{
   hello();
}
于 2012-07-09T22:44:39.893 に答える