C++ 中的友元声明- 公立和私立的区别
将友元函数/类声明为私有或公共有区别吗?我似乎在网上找不到任何关于此的信息。
我的意思是:
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
不,没有什么区别 - 你只需告诉 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.
由于语法
friend class B
没有声明类A
的成员,因此无论你在哪里编写它,classB
是A
类的友元。另外,如果您在
A
的protected
部分写入friend class B
,那么并不意味着B
可以仅访问A
的protected
和public
成员。永远记住,一旦
B
成为A
的好友,它就可以访问A
的任何成员,无论在什么位置您编写friend class B
的部分。Since the syntax
friend class B
doesn't declare a member of the classA
, so it doesn't matter where you write it, classB
is a friend of classA
.Also, if you write
friend class B
inprotected
section ofA
, then it does NOT mean thatB
can access onlyprotected
andpublic
members ofA
.Always remember that once
B
becomes a friend ofA
, it can access any member ofA
, no matter in which section you writefriend class B
.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.
友元声明出现在类主体中,并授予函数或另一个类访问友元声明出现的类的私有和受保护成员的权限。
因此,此类访问说明符对友元声明的含义没有影响(它们可以出现在 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).