好友功能限制

发布于 2024-11-25 05:59:45 字数 105 浏览 4 评论 0原文

根据我引用的文本(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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

情深已缘浅 2024-12-02 05:59:45

派生类不继承友元函数? [...]为什么?

因为这会破坏封装:派生类无法再控制它的朋友,因此它实际上无法控制谁可以访问其内部。

它们不能声明为 static 或 extern,为什么?

因为static没有任何意义(它只在属于类的函数中有意义,并且friend是自由函数),而extern 将再次违反封装性,因为类实际上无法再控制哪个函数可以访问它:由于是 extern,友元实际上可能来自类未知的不同编译单元。

请参阅 Jan 的回答进行更正。

a derived class doesn't inherit friend functions? […] why?

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.

they may not be declared as static or extern, why?

Because static would make no sense (it only makes sense in functions belonging to a class, and friends are free functions), and extern would once again violate encapsulation because the class effectively cannot control any longer which function has access to it: due to being extern, the friend could effectively come from a different compilation unit, unknown to the class.

See Jan’s answer for a correction.

绿萝 2024-12-02 05:59:45
  1. 继承类不会继承友元函数,因为这样做没有意义:
    1. 友元函数本身知道它是友元的类,但它不会神奇地了解新的子类,因此它也不需要成为它的友元。
    2. 由于隐式转换为父类,仍然可以在派生类上使用该函数。
  2. 友元声明不能包含 staticextern,因为它不是函数签名的一部分,因此不需要指定该函数。我相信函数本身的声明(在类之外)可以包含其中任何一个。
  1. Inherit class does not inherit friend functions, because there is no point in doing that:
    1. The friend function itself knows about the class whose friend it is, but it won't magically learn about a new subclass, so it does not need to be it's friend either.
    2. It is still possible to use the function on the derived class due to the implicit conversion to parent.
  2. The friend declaration cannot contain static nor extern, 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.
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文