为什么PRIVATE成员函数不能是另一个类的朋友函数? [英] Why can't a PRIVATE member function be a friend function of another class?
问题描述
class x
{
void xx() {}
};
class y
{
friend void x::xx();
};
这会导致类似
错误:friend function'xx'是'x'的私人成员
error: friend function 'xx' is a private member of 'x'
推荐答案
[class.friend] / 9:
[class.friend]/9:
由朋友声明提名的名称应在包含好友声明的类的
范围内可访问。
A name nominated by a friend declaration shall be accessible in the scope of the class containing the friend declaration.
原因很简单; private
会员必须遵守一个明确而明确的规则:
The reason is quite simple; private
members shall obey a clear and definite rule:
可以
A member of a class can be
-
private
即
private
; that is, its name can be used only by members and friends of the class in which it is declared.
允许私有成员在不是朋友的类中的声明中被命名将是不一致的:它允许另一个类访问实现细节,而不被明确允许。和访问可以意味着从调用到声明的任何东西。
可以通过 x
整个 y
的朋友规避:
Allowing private members to be named in declarations inside a class that isn't a friend would be inconsistent: It allows another class to access an implementation detail without being explicitly allowed to. And "access" can mean anything from a call to a declaration.
This can be circumvented by making x
a friend of y
in its entirety:
class x
{
void xx() {}
};
class y
{
friend x;
};
演示 。
这篇关于为什么PRIVATE成员函数不能是另一个类的朋友函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!