C++ 中的友元声明- 公立和私立的区别

发布于 2024-11-16 08:34:23 字数 267 浏览 1 评论 0原文

将友元函数/类声明为私有或公共有区别吗?我似乎在网上找不到任何关于此的信息。

我的意思是:

class A
{
 public: 
      friend class B;
 };

class A
{
 private: //or nothing as the default is private
      friend class B;
 };

有区别吗?

Is there a difference between declaring a friend function/class as private or public? I can't seem to find anything about this online.

I mean the difference between:

class A
{
 public: 
      friend class B;
 };

and

class A
{
 private: //or nothing as the default is private
      friend class B;
 };

Is there a difference?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(4

百变从容 2024-11-23 08:34:23

不,没有什么区别 - 你只需告诉 B 类是 A 类的友元,现在可以访问其私有和受保护的成员,仅此而已。

No, there's no difference - you just tell that class B is a friend of class A and now can access its private and protected members, that's all.

放飞的风筝 2024-11-23 08:34:23

由于语法 friend class B 没有声明类 A成员,因此无论你在哪里编写它,class BA 类的友元。

另外,如果您在 Aprotected 部分写入 friend class B,那么并不意味着 B 可以仅访问 Aprotectedpublic 成员。

永远记住,一旦B成为A的好友,它就可以访问A任何成员,无论在什么位置您编写friend class B的部分。

Since the syntax friend class B doesn't declare a member of the class A, so it doesn't matter where you write it, class B is a friend of class A.

Also, if you write friend class B in protected section of A, then it does NOT mean that B can access only protected and public members of A.

Always remember that once B becomes a friend of A, it can access any member of A, no matter in which section you write friend class B.

恍梦境° 2024-11-23 08:34:23

c++ 有“隐藏的朋友”的概念: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2019/p1601r0.pdf

仅适用于内联定义的友元函数。这使得函数只能通过依赖于参数的查找来找到,从而将它们从封闭的命名空间中删除。

c++ has the notion of 'hidden friends': http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2019/p1601r0.pdf

Which only applies to friend functions that are defined inline. This make it so the functions can only be found via argument-dependent lookups, removing them from enclosing namespace.

赠我空喜 2024-11-23 08:34:23

友元声明出现在类主体中,并授予函数或另一个类访问友元声明出现的类的私有和受保护成员的权限。

因此,此类访问说明符对友元声明的含义没有影响(它们可以出现在 private: 或 public: 部分中,没有区别)。

The friend declaration appears in a class body and grants a function or another class access to private and protected members of the class where the friend declaration appears.

As such access specifiers have no effect on the meaning of friend declarations (they can appear in private: or in public: sections, with no difference).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文