Specify a class member function as a friend of another class?

后端 未结 7 788
小蘑菇
小蘑菇 2020-12-08 21:43

According to the C++ Primer book, the author mentioned that We can specify a class member function as a friend of another class, instead of the entire class (page 634).

7条回答
  •  一向
    一向 (楼主)
    2020-12-08 22:21

    For this to work, the full definition of B needs to be known before the definition of A.

    So forward declare A, since B doesn't need the full type, and switch the definitions around:

    class A;
    class B
    {
    public:
        void fB(A& a){};
        void fB2(A& a){};
    };
    class A
    {
    public:
        friend void B::fB(A& a);
        void fA(){}
    };
    

提交回复
热议问题