Friend Class In C++

后端 未结 4 687
轮回少年
轮回少年 2021-01-19 19:11

here im not understanding the concept very well or i am right.... So lets take this \"friend\" class example here:

class MyClass{
friend class AnotherClass;
         


        
4条回答
  •  萌比男神i
    2021-01-19 19:53

    friend is for when you don't want to expose getters/setters/internals to everyone, but just to a single class. So it's a tool for encapsulation.

    For example, if you provided a public getSecret in MyClass, everyone could have access to that private variable even if they shouldn't know about it. This breaks encapsulation. friend is there to fix this problem, so that only those classes that need to know about secret have access to it.

    As @nicomp said, "it's like giving your physical friend a key to your house but you don't know what they will do with it". So a friend class has unlimited access to all internals of the class it's friends with. This in unfortunate, but the key (no pun intended) here is to keep classes as small as possible so that this doesn't become a problem, which also would be according to the Single Responsibility Principle.

提交回复
热议问题