When should you use 'friend' in C++?

前端 未结 30 1529
孤街浪徒
孤街浪徒 2020-11-22 10:12

I have been reading through the C++ FAQ and was curious about the friend declaration. I personally have never used it, however I am interested in exploring the language.

30条回答
  •  有刺的猬
    2020-11-22 11:00

    We had an interesting issue come up at a company I previously worked at where we used friend to decent affect. I worked in our framework department we created a basic engine level system over our custom OS. Internally we had a class structure:

             Game
            /    \
     TwoPlayer  SinglePlayer
    

    All of these classes were part of the framework and maintained by our team. The games produced by the company were built on top of this framework deriving from one of Games children. The issue was that Game had interfaces to various things that SinglePlayer and TwoPlayer needed access to but that we did not want expose outside of the framework classes. The solution was to make those interfaces private and allow TwoPlayer and SinglePlayer access to them via friendship.

    Truthfully this whole issue could have been resolved by a better implementation of our system but we were locked into what we had.

提交回复
热议问题