friend class with limited access

后端 未结 3 1876
轮回少年
轮回少年 2020-11-30 02:41

I want to make a class A friend class of class B. I want to do this as these interact very much and A needs to change internals of class B (which I dont want to expose using

相关标签:
3条回答
  • 2020-11-30 03:11

    You can do following thing..

    class A{
    };
    
    class B{
    private: 
        void setFlags();
    protected:
        void setState();
    
    }; 
    
    class RestrictedB :public B{  
        friend class A;
    };
    
    0 讨论(0)
  • 2020-11-30 03:20

    One approach is through explicit interfaces, because the implementor of an interface can select who they give them to:

    class NearlyPrivateInterface {
    public:
       virtual void setState() = 0;
       virtual void setFlags() = 0;
    };
    
    class A {
    public:
       void attach(NearlyPrivateInterface* instanceOfB);
    };
    
    class B: private NearlyPrivateInterface {
    public:
       void attach(A& a) { a.attach(this); }
    };
    
    0 讨论(0)
  • 2020-11-30 03:30

    It depends on what you mean by "a nice way" :) At comp.lang.c++.moderated we had the same question a while ago. You may see the discussion it generated there.

    IIRC, we ended up using the "friend of a nested key" approach. Applied to your example, this would yield:

    class A
    {
    };
    
    class B
    {
    public:
         class Key{
             friend class A;
             Key();
         };
    
        void setFlags(Key){setFlags();}         
    
    private:
      void setState();
      void setFlags();
    };
    

    The idea is that the public setFlags() must be called with a "Key", and only friends of Key can create one, as its ctor is private.

    0 讨论(0)
提交回复
热议问题