2012-01-28 59 views
1

内部クラスメソッドiterateForwardから外部クラス変数cell[i][j]にアクセスしようとしています。C++の内部クラスから外部クラスオブジェクトにアクセスする方法

外部クラスのthisiterateForwarditerateForward(Matrix&)として渡したくないのは、iterateForwardにパラメータを追加するためです。

内部クラスのメソッド:

Pos Matrix::DynamicCellIterator::iterateForward(){ 
        .................... 
     (Example) outerRef.cell[i][j].isDynamic = true;   
        ..................... 
        } 

にここでは、私のクラスである:

class Matrix { 
     class DynamicCellIterator{ 
      Cell* currentCellPtr; 
      Matrix& outerRef; //This will be the key by which i'll get access of outer class variables 
     public: 
      DynamicCellIterator(Matrix&); 
       Pos iterateForward(); 
     }; 
     Cell cell[9][9]; 
     DynamicCellIterator dynIte(*this); // I have a problem of initializing the outerRef variable. 
     Error errmsg; 
     bool consistent; 


    public: 
     Matrix(); 
     Matrix(Matrix&); 
      ................ 
    } 


//Here I tried to initialize the outerRef. 
    Matrix::DynamicCellIterator::DynamicCellIterator(Matrix& ref){ 
     this->currentCellPtr = NULL; 
     this->outerRef = ref; 
    } 

にはどうすればouterRefを初期化することができますか?

+1

ないあなたが取得している何のエラーを確認しますが、私はマトリックス:: DynamicCellIterator :: DynamicCellIterator(行列とREF)を記述します:outerRef(REF)の{ –

+0

可能な重複[内部クラスはプライベート変数にアクセスできますか?](http://stackoverflow.com/questions/486099/can-inner-classes-access-private-variables) –

答えて

4

コンストラクタの初期化リストでメンバー参照を初期化する必要があります。 dynIteメンバでも同じことをやってください:outerのコンストラクタで初期化してください。

このような何か:

class Outer { 
    class Inner { 
     int stuff; 
     Outer &outer; 

     public: 
      Inner(Outer &o): outer(o) { 
       // Warning: outer is not fully constructed yet 
       //   don't use it in here 
       std::cout << "Inner: " << this << std::endl; 
      }; 
    }; 

    int things; 
    Inner inner; 

    public: 
     Outer(): inner(*this) { 
       std::cout << "Outer: " << this << std::endl; 
     } 
}; 
3

内部クラスのコンストラクタに外部クラスのオブジェクトへのポインタを受け入れ、後で使用できるようにデータメンバーに格納します。 (これは本質的にJavaが自動的に行う処理です.btw)

+0

私はこれを試しました。しかし、私はこの行に誤りがあります。 'DynamicCellIterator dynIte(* this);' –

+0

@EAGER_STUDENT:初期化リストを参照する必要があります。 – Puppy

+0

@DeadMG「DynamicCellIterator dynIte(* this);」は無効ですか? 'this'ポインタが関数でのみ使用されることは知っていますが、論理的に' DynamicCellIterator dynIte(* this); 'が無効で、初期化リストでどのように有効であるかを知る必要があります。 –

関連する問題