Nested Class member function can't access function of enclosing class. Why?

后端 未结 4 1680
不知归路
不知归路 2020-12-09 17:02

Please see the example code below:

class A
{
private:
    class B
    {
    public:
        foobar();
    };
public:
    foo();
    bar();
};
4条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-09 17:47

    This is an automagic, albeit possibly nonportable trick (worked on VC++ since 6.0 though). Class B has to be a member of class A for this to work.

    #ifndef OUTERCLASS
    #define OUTERCLASS(className, memberName) \
        reinterpret_cast(reinterpret_cast(this) - offsetof(className, memberName))
    #endif 
    
    class A
    {
    private:
        class B
        {
        public:
            void foobar() {
               A* pA = OUTERCLASS(A, m_classB);
               pA->foo();
            }
        } m_classB;
    public:
        foo();
        bar();
    };
    

提交回复
热议问题