如何从C ++内部类引用封装实例?
在C ++中,对象通过 this
引用自身。
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
我对非静态内部类的工作原理的理解是 Bear
可以访问其 Zoo
的成员,因此它具有 Zoo
的隐式指针。我不想访问这种情况下的成员;我试图得到那个隐含的指针。
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.
与Java不同,C ++中的内部类不会隐式引用它们的实例
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 :
方法:
class Zoo
{
class Bear
{
void runAway( Zoo & zoo)
{
EscapeService::helpEscapeFrom (
this, /* the Bear */
zoo );
}
};
};
传递给构造函数:
class Zoo
{
class Bear
{
Bear( Zoo & zoo_ ) : zoo( zoo_ ) {}
void runAway()
{
EscapeService::helpEscapeFrom (
this, /* the Bear */
zoo );
}
Zoo & zoo;
};
};