2012-01-28 137 views
1

我正试图从内部类方法iterateForward访问外部类变量cell[i][j]如何从C++的内部类访问外部类对象

我不希望外部类的传递thisiterateForward作为iterateForward(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){ – 2012-01-28 17:37:12

+0

的可能的复制[内部类可以访问私有变量?](http://stackoverflow.com/questions/486099/can-inner-classes-access-private-variables) – 2016-10-31 23:18:07

回答

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在引擎盖下自动执行的操作)。

+0

我只试过这个。但我在这一行中出现错误。 'DynamicCellIterator dynIte(* this);' – 2012-01-28 17:42:34

+0

@EAGER_STUDENT:您需要查看初始化列表。 – Puppy 2012-01-28 17:48:34

+0

@DeadMG你能告诉我吗?DynamicCellIterator dynIte(* this);'无效?虽然我知道'this'指针只能用于函数,但我需要知道,'DynamicCellIterator dynIte(* this)'在逻辑上如何无效,以及它在初始化列表中的有效性如何。 – 2012-01-28 17:59:20