好友功能限制
根据我引用的文本(Herbert Schildt 的《完整参考》),派生类不会继承友元函数,并且友元函数可能没有 存储类说明符。也就是说,它们不能被声明为 static 或 extern。为什么?
According to the text I am referring to (The Complete Reference by Herbert Schildt) a derived class doesn't inherit friend functions and friend functions may not have a
storage-class specifier. That is, they may not be declared as static or extern. Why?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
因为这会破坏封装:派生类无法再控制它的朋友,因此它实际上无法控制谁可以访问其内部。
因为static
没有任何意义(它只在属于类的函数中有意义,并且friend
是自由函数),而extern 将再次违反封装性,因为类实际上无法再控制哪个函数可以访问它:由于是
extern
,友元实际上可能来自类未知的不同编译单元。请参阅 Jan 的回答进行更正。
Because that would break encapsulation: the derived class couldn’t control its friends any longer so it effectively cannot control who has access to its internals.
Becausestatic
would make no sense (it only makes sense in functions belonging to a class, andfriend
s are free functions), andextern
would once again violate encapsulation because the class effectively cannot control any longer which function has access to it: due to beingextern
, the friend could effectively come from a different compilation unit, unknown to the class.See Jan’s answer for a correction.
static
或extern
,因为它不是函数签名的一部分,因此不需要指定该函数。我相信函数本身的声明(在类之外)可以包含其中任何一个。static
norextern
, because it is not part of the function signature, so it's not needed to specify the function. I believe the declaration of the function itself can (outside of the class) contain either.