Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
369 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 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...