C++朋友继承?
子类是否继承主类的友元关联(主类自己的以及与主类成为友元的其他类)?
或者换句话说,继承如何应用于friend关键字?
展开: 如果没有的话,有什么办法可以继承友谊吗?
我按照乔恩的建议发布了设计问题:
C++ 类设计问题
Does a subclass inherit, the main class' friend associations (both the main class' own and other classes friended with the main class)?
Or to put it differently, how does inheritance apply to the friend keyword?
To expand:
And if not, is there any way to inherit friendship?
I have followed Jon's suggestion to post up the design problem:
C++ class design questions
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
C++ 中的友谊不是继承的。
该标准规定(ISO/IEC 14882:2003,第 11.4.8 节):
Friendship is not inherited in C++.
The standard says (ISO/IEC 14882:2003, section 11.4.8):
您可以在父级中创建(静态)受保护的方法,这将允许您执行类似的操作。
然而,这绕过了封装,因此您可能应该重新审视您的设计。
You can create (static) protected methods in the parent that will allow you to do things like that.
This however bypasses encapsulation so you probably should take a second look at your design.
朋友仅适用于您明确将其设为朋友的班级,而不适用于其他班级。
http://www.parashift.com/c++-faq-lite /friends.html#faq-14.4
friend only applies to the class you explicitly make it friend and no other class.
http://www.parashift.com/c++-faq-lite/friends.html#faq-14.4
答案很简单:不,子类不会继承友元关联。朋友只能访问声明关联的类的私有成员,而不能访问该类的父级和/或子级的私有成员。虽然您可能是超类的访问受保护成员,但我不确定这一点。
The answer is very simple: no, subclasses do not inherit friend associations. A friend can only access the private members of the class the association is declared in, not those of parents and/or children of that class. Although you might be access protected member of a superclass, but I'm not sure about that.