本文介绍了C ++中的朋友类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在这里我不太了解这个概念,或者我是对的....因此,让我们在这里以朋友"类示例为例:

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;
private:
       int secret;
}

class AnotherClass{
public:
      void getSecret(MyClass mc){
          return mc.secret;
      }
}

是的...在上面的代码中,如果您这样做,它实际上将起作用...但是,总的来说,为什么不能一直使用getter和setter而不是friend class?难道是因为乏味"而使用朋友类吗?

So Yes... in the above code it will actually work if you do it... but in general, why cant you use getters and setters all the time instead of friend class? Is the reason of friend class usage because of "tediousness"?

推荐答案

friend适用于您不想将getters/setters/internals暴露给所有人,而只暴露给单个类的情况.因此,这是一种封装工具.

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.

例如,如果您在MyClass中提供了公共getSecret,那么即使每个人都不知道该私有变量,每个人都可以访问该私有变量.这破坏了封装. friend可以解决此问题,因此只有那些需要了解secret的类才可以访问它.

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.

正如@nicomp所说,这就像给您的亲密朋友一个房子的钥匙,但您不知道他们会怎么做".因此,friend类可以不受限制地访问与其朋友一起使用的类的所有内部.不幸的是,但是这里的关键(不要双关语)是使类尽可能的小,这样才不会成为问题,这也符合单一职责原则".

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.

这篇关于C ++中的朋友类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 18:42