[英]How to access the outer class object from the inner class in c++
I am trying to access the outer class variable cell[i][j]
from the inner class method iterateForward
. 我试图从内部类方法
iterateForward
访问外部类变量cell[i][j]
。
I do not want to pass this
of outer class to iterateForward
as iterateForward(Matrix&)
, since it will add a parameter to iterateForward. 我并不想通过
this
外部类的iterateForward
为iterateForward(Matrix&)
,因为它会添加参数iterateForward。
Inner class Method: 内部类方法:
Pos Matrix::DynamicCellIterator::iterateForward(){
....................
(Example) outerRef.cell[i][j].isDynamic = true;
.....................
}
Here is my class: 这是我的课:
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;
}
How can I initialize outerRef
? 我如何初始化
outerRef
?
You need to initialize member references in the constructor's initialization list. 您需要在构造函数的初始化列表中初始化成员引用。 And do the same for the
dynIte
member: initialize it in outer's constructor. 并对
dynIte
成员执行相同dynIte
:在dynIte
的构造函数中对其进行初始化。
Something like this: 像这样:
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;
}
};
Have the constructor of the inner class accept a pointer to an object of the outer class and store it in a data member for later use. 让内部类的构造函数接受指向外部类对象的指针,并将其存储在数据成员中以备后用。 (This is essentially what Java does automatically under the hood, btw.)
(本质上,这是Java在后台自动执行的操作。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.