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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 20:05:10  来源:igfitidea点击:

Friend declaration in C++ - difference between public and private

c++privatefriendpublic

提问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 Bdoesn't declare a memberof the class A, so it doesn't matter where you write it, class Bis a friend of class A.

由于语法friend class B没有声明class的成员A,所以不管你在哪里写它, classB是class的朋友A

Also, if you write friend class Bin protectedsection of A, then it does NOT mean that Bcan access only protectedand publicmembers of A.

此外,如果您friend class B在 的protected部分中写入A,那么这并不意味着B只能访问protected和 的public成员A

Always remember that once Bbecomes 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: 部分,没有区别)。