C ++从嵌套类方法访问变量 [英] c++ accessing variable from nested class method

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

问题描述

如何从其嵌套类方法访问类属性?

How can I access class attribute from its nested class method?

class Class1
{
public:
    int attribute;
    void Method1() { 
        class Class2
        {
            public:
               void Method2() { 
                   //here I need to access attribute from Class1
               }
        };
    }
};

推荐答案

您可以将this传递给内部类.例如:

You can pass this to the inner class. For example:

class Class1
{
public:
    Class1() : class2(this) {
    }

    int attribute;
    void Method1() { 
    };

    class Class2
    {
        Class1 *parent;
    public:
        Class2(Class1 *parent) : parent(parent) {
        }
        void Method2() { 
             // parent->attribute
        }
   } class2;
};

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

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