【问题标题】:How to access the outer class object from the inner class in c++如何从C++中的内部类访问外部类对象
【发布时间】:2012-01-28 17:29:42
【问题描述】:

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

我不想将外部类的 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

【问题讨论】:

标签: c++ inner-classes


【解决方案1】:

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

    • 我只试过这个。但我在这条线上遇到了错误。 DynamicCellIterator dynIte(*this);
    • @EAGER_STUDENT:你需要查找初始化列表。
    • @DeadMG 你能告诉我DynamicCellIterator dynIte(*this); 无效吗?虽然我知道this 指针只会在函数中使用,但我需要知道DynamicCellIterator dynIte(*this); 在逻辑上如何无效以及在初始化列表中如何有效。
    • 向我们展示DynamicCellIterator的构造函数。
    猜你喜欢
    • 1970-01-01
    • 2011-01-02
    • 2021-07-24
    • 2021-06-09
    • 1970-01-01
    • 2011-02-13
    • 2017-05-31
    • 1970-01-01
    相关资源
    最近更新 更多