简体   繁体   English

C ++中的Friend函数

[英]Friend function in c++

Why we always say that friend function are not member function even though they are declared in the class? 为什么我们总是说即使在类中声明了朋友函数也不是成员函数? I have found in many books and on internet but i am not getting proper explanation. 我在很多书和互联网上都找到了,但是我没有得到适当的解释。

friend (C++) 朋友(C ++)

If you declare a friend function that was not previously declared, that function is exported to the enclosing nonclass scope. 如果声明的朋友函数以前未声明,则该函数将导出到封闭的非类范围。

In [class.mfct] the C++ standard says (or said around the time of C++11. The link's bit out of date at this point) [class.mfct]中 ,C ++标准说(或大约在C ++ 11的时间说。链接此时已过时)

Functions declared in the definition of a class, excluding those declared with a friend specifier ( [class.friend] ), are called member functions of that class. 在类的定义中声明的函数(不包括用friend指定符( [class.friend] )声明的函数)称为该类的成员函数。

I'm having difficulty finding similar wording in later drafts of the standard. 我很难在以后的标准草案中找到类似的措词。

That said, I consider this one self-evident. 也就是说,我认为这是不言而喻的。

[class.friend] states: [class.friend]指出:

A friend of a class is a function or class that is given permission to use the private and protected member names from the class. 类的朋友是被授予使用该类的私有和受保护成员名称的权限的函数或类。 A class specifies its friends, if any, by way of friend declarations. 类通过朋友声明来指定其朋友(如果有)。 Such declarations give special access rights to the friends, but they do not make the nominated friends members of the befriending class. 此类声明为朋友提供了特殊的访问权限,但它们并未使被提名的朋友成为朋友班的成员。

A friend is something outside the class that has been granted access by the class to the protected and private members of the class. friend是类之外的东西,该类已被该类授予其受保护的成员和私有成员的访问权限。 This implies that a friend is not a member itself. 这意味着friend本身不是成员。

Note also that the friend function does not have to be implemented within the class. 还要注意,不必在类中实现friend函数。 A declaration is sufficient. 声明就足够了。

Conceptually, a member function is of type Ret(Class::*)(Args...) , is called on an instance of the class: instance.member_function() , and has access to the called instance via this . 从概念上讲,成员函数的类型为Ret(Class::*)(Args...) ,在类的实例: instance.member_function()上调用,并可以通过this来访问被调用的实例。 A friend function doesn't fit with "member functions". 朋友功能不适合“成员功能”。 The function is defined in a separate scope and not in the class even though it looks similar to a member function declaration. 该函数在单独的作用域中定义,而不是在类中定义,即使它看起来类似于成员函数声明。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM