English 中文(简体)
如何从C++内部类引用封闭实例?
原标题:How to refer to enclosing instance from C++ inner class?

在C++中,一个对象通过this引用自己。

但是,内部类的实例是如何引用其封闭类的实例的呢?

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

编辑

我对非静态内部类如何工作的理解是,Bear可以访问其Zoo的成员,因此它有一个指向Zoo

最佳回答

与Java不同,C++<em>中的内部类不具有对其封闭类实例的隐式引用。

您可以通过传递实例来模拟此情况,有两种方法:

传递到方法:

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;
    };
}; 
问题回答

内部类并不是特别的,并且没有任何到它们的外部类的链接。如果你想访问外部类,那么就传递一个指针或引用,就像你对任何其他类一样。

You can access the outer class instance from an inner class instance by using offsetof.
This has zero overhead compared to the pointer/reference solution.
It s a bit dirty but it gets the job done.
For example:

#include <cstddef>
struct enclosing {
    struct inner {
        enclosing& get_enclosing() {
            return *(enclosing*)((char*)this - offsetof(enclosing, i));
        }
        void printX() {
            std::cout << get_enclosing().x <<  
 ;
        }
    } i;
    int x;
};
int main() {
    enclosing e;
    e.x = 5;
    e.i.printX();
}

P.S.
offsetof makes some assumptions about the type. In C++98 the type has to be a POD and in C++11 the type has to be "standard layout".
Here s a reference: http://www.cplusplus.com/reference/cstddef/offsetof/

内部类可以访问外部类的所有成员,但它没有对父类实例的隐式引用。

To answer your modifed Q:
No you cannot access that implicit pointer. I believe one can do so in Java but not in C++.

您必须通过构造函数或其他函数显式传递外部类对象才能实现这一点。

从技术上讲,根据C++03标准(第11.8.1节),嵌套类对其封闭类没有特殊访问权限。

但也有这个标准缺陷:openstd.org/jtc1/sc22/wg21/docs/cwg_defaults.html#45不确定这是否已经关闭。

没有实现这一点的内置机制。您需要通过构造函数或某种SetParent函数自己提供指针。

C++标准规定(第11.8.1节[class.access.nest]):

The members of a nested class have no special access to members of an enclosing class, nor to classes or functions that have granted friendship to an enclosing class; the usual access rules (clause 11) shall be obeyed. The members of an enclosing class have no special access to members of a nested class; the usual access rules (clause 11) shall be obeyed.

(我强调)。

这意味着嵌套类和封闭类之间没有特殊的关系。

在创建嵌套类的实例时,没有隐式创建的封闭类实例。必须手动完成。





相关问题
Undefined reference

I m getting this linker error. I know a way around it, but it s bugging me because another part of the project s linking fine and it s designed almost identically. First, I have namespace LCD. Then I ...

C++ Equivalent of Tidy

Is there an equivalent to tidy for HTML code for C++? I have searched on the internet, but I find nothing but C++ wrappers for tidy, etc... I think the keyword tidy is what has me hung up. I am ...

Template Classes in C++ ... a required skill set?

I m new to C++ and am wondering how much time I should invest in learning how to implement template classes. Are they widely used in industry, or is this something I should move through quickly?

Print possible strings created from a Number

Given a 10 digit Telephone Number, we have to print all possible strings created from that. The mapping of the numbers is the one as exactly on a phone s keypad. i.e. for 1,0-> No Letter for 2->...

typedef ing STL wstring

Why is it when i do the following i get errors when relating to with wchar_t? namespace Foo { typedef std::wstring String; } Now i declare all my strings as Foo::String through out the program, ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

Window iconification status via Xlib

Is it possible to check with the means of pure X11/Xlib only whether the given window is iconified/minimized, and, if it is, how?