嵌套的内部类访问外部类 [英] Nested inner class access to outer class

查看:79
本文介绍了嵌套的内部类访问外部类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  • 我有一个嵌套类,需要操纵其外部类的数据成员.
  • 我要求外部类具有空的构造函数.
  • 以下版本可以正常编译
  • 有什么方法可以避免在Inner中使用Outer *o并使用Outer o吗?
  • I have a nested class that needs to manipulate the data members of its outer class.
  • I demand that the outer class will not have an empty constructor.
  • The following version compiles fine
  • Is there any way to avoid using Outer *o inside Inner, and use Outer o?
class Outer {
private:
    class Inner {
    private: Outer *o;
    public:
        Inner(Outer *outer):o(outer){}
        void visit() { o->d=65; }
    };
private:
    int d;
    Inner v;
public:
    Outer(int m):d(m),v(this){}
};

int main(int argc, char **argv)
{
    Outer out(16);
    return 0;
}

推荐答案

否,如果您创建一个新实例,则情况将是周期性的.但是,您可以使用引用,而不是使用指向外部类的指针:

No, if you create a new instance, the situation will become cyclic. Instead of using pointer to the outer class, you can however use a reference, like so:

class Outer {
private:
    class Inner{
    private:
        Outer& o;
    public:
        Inner(Outer& outer) :o(outer) {}
        void visit() { o.d = 65; }
    };
private:
    int d;
    Inner v;
public:
    Outer(int m) :d(m), v(*this) {}
};

int main(int argc, char **argv)
{
    Outer out(16);
    return 0;
}

这篇关于嵌套的内部类访问外部类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆