私人嵌套类中的朋友 [英] Friend within private nested class

查看:115
本文介绍了私人嵌套类中的朋友的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个私人嵌套类,需要访问另一个类中的私有成员。我考虑把需要访问私人成员的类作为访问类中的朋友,但是我得到一个错误,A :: m_nData是私有的,所以我不能访问它。无论如何告诉编译器,我需要访问D :: DoSomething()中的A :: m_nData私有成员?



这里是我试图做:



档案

  class A 
{
class D;

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

private:
friend class D;

int m_nData;
};

档案 A.cpp:

  #includeAh
#includeBh

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

文件 Bh:

  #includeAh

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 ++;
};
};
};


解决方案

strong>让 A 知道私人 B :: D ,另一个让 B :: D 访问 A 中的私人数据。




b $ b

 朋友类A; 

这允许A类知道私人 B :: D



然后在 A类中替换:

 朋友类D; 

其中:

 code> friend class B :: D; 


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++;
                };
        };
};

解决方案

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;

这篇关于私人嵌套类中的朋友的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆