Ton*_*ony 9 c++ this inner-classes
在C++中,对象通过引用自身this.
但是内部类的实例如何引用其封闭类的实例?
class Zoo
{
class Bear
{
void runAway()
{
EscapeService::helpEscapeFrom (
this, /* the Bear */
??? /* I need a pointer to the Bear's Zoo here */);
}
};
};
Run Code Online (Sandbox Code Playgroud)
编辑
我对非静态内部类如何工作的理解是Bear可以访问它的成员Zoo,因此它有一个隐式指针Zoo.在这种情况下我不想访问成员; 我正试图得到那个隐含的指针.
BЈо*_*вић 17
与Java不同,C++中的内部类没有对其封闭类的实例的隐式引用.
您可以通过传递实例来模拟这个,有两种方法:
传递给方法:
class Zoo
{
class Bear
{
void runAway( Zoo & zoo)
{
EscapeService::helpEscapeFrom (
this, /* the Bear */
zoo );
}
};
};
Run Code Online (Sandbox Code Playgroud)
传递给构造函数:
class Zoo
{
class Bear
{
Bear( Zoo & zoo_ ) : zoo( zoo_ ) {}
void runAway()
{
EscapeService::helpEscapeFrom (
this, /* the Bear */
zoo );
}
Zoo & zoo;
};
};
Run Code Online (Sandbox Code Playgroud)
内部类可以访问外部类的所有成员,但它没有对父类实例的隐式引用.
要回答你修改过的Q:
不,你不能访问那个隐式指针.我相信人们可以用Java来实现,但不能用C++实现.
您必须通过构造函数或其他函数显式传递外部类对象才能实现此目的.
从技术上讲,根据C++ 03标准(sec 11.8.1),嵌套类没有对其封闭类的特殊访问权限.
但也存在这个标准缺陷:openstd.org/jtc1/sc22/wg21/docs/cwg_defects.html#45不确定是否已关闭.
您可以使用offsetof从内部类实例访问外部类实例。
与指针/引用解决方案相比,这具有零开销。
它有点脏,但是可以完成工作。
例如:
#include <cstddef>
struct enclosing {
struct inner {
enclosing& get_enclosing() {
return *(enclosing*)((char*)this - offsetof(enclosing, i));
}
void printX() {
std::cout << get_enclosing().x << '\n';
}
} i;
int x;
};
int main() {
enclosing e;
e.x = 5;
e.i.printX();
}
Run Code Online (Sandbox Code Playgroud)
PS
offsetof对类型做了一些假设。在C ++ 98中,类型必须是POD,而在C ++ 11中,类型必须是“标准布局”。
这是参考:http : //www.cplusplus.com/reference/cstddef/offsetof/
| 归档时间: |
|
| 查看次数: |
6298 次 |
| 最近记录: |