什么时候用C ++中的friend类 [英] When to use friend class in C++

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

问题描述


可能重复:

何时在C ++中使用friend?




$ b b

我正在刷新我的C ++(我是一个Java开发人员),我遇到了我已经忘记了一段时间的朋友类关键字。这是那些功能只是厨房水槽的一部分,或有一个很好的理由这样做,而不只是一个香草吸气器?我明白,它限制了谁可以访问数据,但我不能想到这是必要的情况下的差异。

I was brushing up on my C++ (I'm a Java developer) and I came across the friend class keyword which I had forgotten about for a while. Is this one of those features that's just part of the kitchen sink, or is there a good reason for doing this rather than just a vanilla getter? I understand the difference in that it limits who can access the data, but I can't think of a scenario when this would be necessary.

注意:我见过一个类似的问题,但特别是我问,这只是一个高级功能,除了让人们看到你的代码,直到他们意识到你在做什么,才会增加没有真正的价值?

Note: I've seen a similar question, but specifically I'm asking, is this just an advanced feature that adds no real value except to confuse people looking at you're code until they realize what you're doing?

推荐答案

我同意的朋友关键字可以改善封装,如果明智使用的意见。我只是补充说,最常见的(合法!)用于朋友类可能是测试。您可能希望测试程序类具有比其他客户端类更大程度的访问。测试者类可以有很好的理由来查看内部细节,这些细节是故意从其他类中隐藏的。

I agree with the comments that say the friend keyword can improve encapsulation if used wisely. I'd just add that the most common (legitimate!) use for friend classes may be testing. You may want a tester class to have a greater degree of access than other client classes would have. A tester class could have a good reason to look at internal details that are deliberately hidden from other classes.

这篇关于什么时候用C ++中的friend类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆