Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
363 views
in Technique[技术] by (71.8m points)

this - How to refer to enclosing instance from C++ inner class?

In C++, an object refers to itself via this.

But how does an instance of an inner class refer to the instance of its enclosing class?

class Zoo
{
    class Bear 
    {
        void runAway()
        {
            EscapeService::helpEscapeFrom (
                this, /* the Bear */ 
                ??? /* I need a pointer to the Bear's Zoo here */);
        }
    };
};

EDIT

My understanding of how non-static inner classes work is that Bear can access the members of its Zoo, therefore it has an implicit pointer to Zoo. I don't want to access the members in this case; I'm trying to get that implicit pointer.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Unlike Java, inner classes in C++ do not have an implicit reference to an instance of their enclosing class.

You can simulate this by passing an instance, there are two ways :

pass to the method :

class Zoo
{
    class Bear 
    {
        void runAway( Zoo & zoo)
        {
            EscapeService::helpEscapeFrom (
                this, /* the Bear */ 
                zoo );
        }
    };
}; 

pass to the constructor :

class Zoo
{
    class Bear
    {
        Bear( Zoo & zoo_ ) : zoo( zoo_ ) {}
        void runAway()
        {
            EscapeService::helpEscapeFrom (
                this, /* the Bear */ 
                zoo );
        }

        Zoo & zoo;
    };
}; 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...