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

时间:2012-01-28 17:29:43

标签: c++ inner-classes

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

我不想将this外部类传递给iterateForward作为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

2 个答案:

答案 0 :(得分:4)

您需要在构造函数的初始化列表中初始化成员引用。并对dynIte成员执行相同操作:在外部构造函数中初始化它。

这样的事情:

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;
        }
};

答案 1 :(得分:3)

让内部类的构造函数接受指向外部类对象的指针,并将其存储在数据成员中供以后使用。 (这基本上就是Java在引擎盖下自动执行的操作,顺便说一句。)