Friend within private nested class

别来无恙 提交于 2020-01-01 22:46:09

问题


I have two private nested classes that would need to access a private member in another class. I thought about putting the class that needs to access the private member as friend in the accessed class, however I'm getting an error that A::m_nData is private so I can't access it. Anyway of telling the compiler that I need to access the A::m_nData private member within D::DoSomething()?

Here is a sample of what I'm trying to do:

File A.h

class A
{
    class D;

    public:
        A();
        ~A() {}

    private:
        friend class D;

        int m_nData;
};

File A.cpp:

#include "A.h"
#include "B.h"

A::A()
:   m_nData(0)
{
}

File B.h:

#include "A.h"

class B
{
    public:
        B() {}
        ~B() {}

    private:
        class C
        {
            public:
                C(A* pA): m_pA(pA) {}
                virtual ~C() {}
                virtual void DoSomething() {}

            protected:
                A* m_pA;
        };

        class D: public C
        {
            public:
                D(A* pA): C(pA) {}
                virtual ~D() {}
                virtual void DoSomething()
                {
                    m_pA->m_nData++;
                };
        };
};

回答1:


You need two friendships here. One to let A know about the private B::D and another to let B::D access private data in A.

Declare (include) class B before declaring class A.

Then in class B, add:

friend class A;

This allows class A to know about the private B::D.

Then in class A, replace:

friend class D;

with:

friend class B::D;


来源:https://stackoverflow.com/questions/8760181/friend-within-private-nested-class

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!