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

后端 未结 7 750
小蘑菇
小蘑菇 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:18

    Try putting the B definition before A's:

    class A; // forward declaration of A needed by B
    
    class B
    {
    public:
        // if these require full definition of A, then put body in implementation file
        void fB(A& a); // Note: no body, unlike original.
        void fB2(A& a); // no body.
    };
    
    class A
    {
    public:
        friend void B::fB(A& a);
        void fA(){}
    };
    

    A needs the full definition of B. However, B needs to know about A, but does not need the full definition, so you need the forward declaration of A.

提交回复
热议问题