C ++允许好友的派生类可以访问私有嵌套类 [英] C++ allow derived classes of friend to have access to private nested class

查看:81
本文介绍了C ++允许好友的派生类可以访问私有嵌套类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这就是我想要做的:

class A
{
    friend class C (and all of C's derived classes)
public:
    void DoAThing() { mpMyC->DelegateResponsibility(myB); }   

private:
   class B
   {
   };
   B mMyB;
   C* mpMyC;  
};

class C
{
    // No problem here- C can see B
    virtual void DelegateResponsibility(const A::B& necessaryInfo);
};

class D: public C
{
    // Uh-oh- we don't inherit friendship   
    virtual void DelegateResonsibility(const A::B& necessaryInfo);
};

简而言之,我在A内有一个私有的嵌套类,因为它是A的实现细节.但是,我想将A的某些职责委派给C和C的派生类,以获得一些多态行为.我想避免每次有人从C派生时都必须添加一个朋友类行.为派生的朋友类提供的标准解决方法是仅将一个受保护的访问器函数添加到您的基类中,并为派生成员覆盖它"帮助访问A类的私有成员,而不是私有范围的类.有什么方法可以解决此问题?

In short, I have a private nested class inside A because it's an implementation detail of A. However, I'd like to delegate some responsibilities of A to C and C's derived classes to get some polymorphic behavior. I'd like to avoid having to add a friend class line every time someone derives from C. The standard workaround given for derived friend classes is "just add a protected accessor function to your base class and override it for derived members" but that only helps access private members of class A, not privately scoped classes. Is there any way to workaround this issue?

推荐答案

这应该有效:

class C
{
    typedef A::B MyB;
    virtual void DelegateResponsibility(const MyB& necessaryInfo);
};

class D: public C
{
    // Uh-oh- we don't inherit friendship   
    virtual void DelegateResonsibility(const MyB& necessaryInfo);
};

这篇关于C ++允许好友的派生类可以访问私有嵌套类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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