Allowing a “friend” class to access only some private members

前端 未结 7 1821
迷失自我
迷失自我 2020-12-13 12:54

Suppose I have three C++ classes FooA, FooB and FooC.

FooA has an member function named Hello, I want to call this function in class FooB, but I don\'t

7条回答
  •  时光取名叫无心
    2020-12-13 13:52

    You can partially expose a class's interfaces to a specified client by inherit it from an interface class.

    class FooA_for_FooB
    {
    public:
        virtual void Hello() = 0;
        virtual void Hello2() = 0;
    };
    
    class FooA : public FooA_for_FooB
    {
    private: /* make them private */
        void Hello() override;
        void Hello2() override;
    private:
        void Hello3();
        int m_iData;
    };
    
    class FooB
    {
        void fun()
        {
            FooA objA;
            FooA_for_FooB &r = objA;
            r.Hello()  // right
            r.Hello2() // right
            objA.Hello3() // compile error
            objA.m_iData = 0; // compile error
        }
    };
    
    class FooC
    {
        void fun()
        {
            FooA objA;
            objA.Hello()  // compile error
            objA.Hello2() // compile error
            objA.Hello3() // compile error
            objA.m_iData = 0; // compile error
        }
    };
    

    Here access control is enhanced by the base class FooA_for_FooB. By a reference of type FooA_for_FooB, FooB can access the members defined within FooA_for_FooB. However, FooC cannot access those members since they have been override as private members in FooA. Your purpose can be achieved by not using the type FooA_for_FooB within FooC, or any other places except FooB, which can be kept without paying much attention.

    This approach needs no friend, making things simple.

    A similar thing can be done by making everything private in a base class, and selectively wrap-and-expose some of the members as public in the derived class. This approach may sometimes require ugly downcast, though. (Because the base class will become the "currency" among the whole program.)

提交回复
热议问题