Friend scope in C++

前端 未结 5 924
萌比男神i
萌比男神i 2020-11-28 06:05

If I have three classes, A, B, C. A and B are friends (bidirectionally). Also, B and C are friends (bidirectionally). A has a pointer to B and B has a pointer to C. Why can\

5条回答
  •  孤独总比滥情好
    2020-11-28 06:56

    Friendship in C++ is not transitive:

    (A is friend of B) and (B is friend of C) does not mean (A is friend of C)
    

    Also, friendship is not symmetric.

    (A is friend of B) does not mean (B is friend of A) 
    

    You have to explicitly state that A is a friend of C to be able to access C's private stuff from within A. If adding a setter and getter to a class exposes information not meant to be exposed, you should consider friends if you can't find your design being faulty (using friend is valid. It's not a sign for bad design). If you can add a setter and getter without that being destructive to the interface, then you should avoid making other classes friends. Note that a nested class is always a friend of the nesting class. So a nested class can see the privates of the nesting class.

提交回复
热议问题