gpt4 book ai didi

c++ - C++中如何从内部类访问外部类对象

转载 作者:行者123 更新时间:2023-11-30 00:39:18 30 4
gpt4 key购买 nike

我正在尝试从内部类方法 iterateForward 访问外部类变量 cell[i][j]

我不想将外部类的 this 作为 iterateForward(Matrix&) 传递给 iterateForward ,因为它会向 iterateForward 添加一个参数.

内部类方法:

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

这是我的类(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;
}

如何初始化 outerRef

最佳答案

您需要在构造函数的初始化列表中初始化成员引用。对 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;
}
};

关于c++ - C++中如何从内部类访问外部类对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9047302/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com