简体   繁体   English

c ++从嵌套类方法访问变量

[英]c++ accessing variable from nested class method

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

You can pass this to the inner class. 你可以通过this来的内部类。 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;
};

Following is one way of doing it with minor changes to OP's code. 以下是对OP代码进行微小更改的一种方法。

#include <cassert>

class Class1
{
    public:
        Class1( int attribute ) : attribute_( attribute ) {
        }
        void Method1() { 
            class Class2
            {
                public:
                    Class2( Class1 * parent ) : parent_( parent ) {
                    }
                    int parentAttribute() const { 
                        return parent_->attribute_;
                    }
                private:
                    Class1 * parent_;
            };
            Class2 c2( this );
            assert( c2.parentAttribute() == attribute_ );
        }
    private:
        int attribute_;
};

int main() {
    Class1 c1( 42 );;
    c1.Method1();
}

The code is also posted at http://codepad.org/MUF3a8jL 该代码也发布在http://codepad.org/MUF3a8jL

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM