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

标签 c++ inner-classes

我正在尝试从内部类方法 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/

相关文章:

c++ - 如何打印数组的所有连续子数组

java - 如何访问外部外部类(非外部类)属性?

java - 如何在 Java 内部类中定义绑定(bind)类型参数

java - 在外部类中创建内部类对象成员后如何访问内部类对象成员

java - 嵌套 Java 内部类的深度超过一层是否合理?

c++ - 当我使用按引用返回时,我不知道这些代码之间的区别

c++ - omp_get_max_threads() 在并行区域返回 1,但它应该是 8

c++ - 当短路评估可能导致函数未被调用时,是否有 gcc 警告标志?

c++ - 难以阅读两行代码

c++ - 如何访问 C++ 中的私有(private)嵌套类?