ローカル・クラス

C++ローカル・クラス は、関数定義の中で宣言されます。 ローカル・クラスでの宣言が使用できるのは、外部変数および関数に加えて、 囲みスコープからの型名、列挙、静的変数だけです。

次に例を示します。

int x;                         // global variable
void f()                       // function definition
{
      static int y;            // static variable y can be used by
                               // local class
      int x;                   // auto variable x cannot be used by
                               // local class
      extern int g();          // extern function g can be used by
                               // local class
 
      class local              // local class
      {
            int g() { return x; }      // error, local variable x
                                       // cannot be used by g
            int h() { return y; }      // valid,static variable y
            int k() { return ::x; }    // valid, global x
            int l() { return g(); }    // valid, extern function g
      };
}
 
int main()
{
      local* z;                // error: the class local is not visible
      // ...}

ローカル・クラスのメンバー関数は、メンバー関数が定義される場合、そのクラス定義の中で定義 してください。結果として、ローカル・クラスのメンバー関数は、インライン関数です。 ローカル・クラスの スコープの中で定義されているメンバー関数は、すべてのメンバー関数と 同様に、キーワード inline は必要ありません。

ローカル・クラスが静的データ・メンバーを持つことはできません。以下の例において、ローカル・クラスの 静的メンバーを定義しようとすると エラーになります。

void f()
{
    class local
    {
       int f();              // error, local class has noninline
                             // member function
       int g() {return 0;}   // valid, inline member function
       static int a;         // error, static is not allowed for
                             // local class
       int b;                // valid, nonstatic variable
    };
}
//      . . .

囲み関数は、ローカル・クラスのメンバーに特別なアクセスを行いません。

関連参照

IBM Copyright 2003