C++ 中的朋友声明 - 公共和私人之间的区别
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6407691/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Friend declaration in C++ - difference between public and private
提问by BIU
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?
有区别吗?
采纳答案by sharptooth
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.
不,没有区别 - 您只需告诉 B 类是 A 类的朋友,现在可以访问其私有成员和受保护成员,仅此而已。
回答by Nawaz
Since the syntax friend class B
doesn't declare a memberof the class A
, so it doesn't matter where you write it, class B
is a friend of class A
.
由于语法friend class B
没有声明class的成员A
,所以不管你在哪里写它, classB
是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
.
此外,如果您friend class B
在 的protected
部分中写入A
,那么这并不意味着B
只能访问protected
和 的public
成员A
。
Always remember that once B
becomes a friend of A
, it can access anymember of A
, no matter in which section you write friend class B
.
永远记住,一旦B
成为朋友A
,它就可以访问任何成员A
,无论你写在哪个版块friend class B
。
回答by goyuiitv
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).
因此,访问说明符对友元声明的含义没有影响(它们可以出现在 private: 或 public: 部分,没有区别)。