简体   繁体   English

如何在c++中使用/访问class的内部朋友function?

[英]How to use/access inner friend function of class in c++?

We can declare and define a friend function inside a class, like below我们可以在 class 中声明和定义一个朋友 function,如下所示

class C
{
    friend void F() {cout<<"inner friend func"<<endl;}
};

how to access/use this inner friend func?如何访问/使用这个内心的朋友功能?

C::F() //error: 'F' is not a member of 'C'
C().F()//error: 'class C' has no member named 'F'

The friend decalration declares F() as non-member function, then both C::F() and C().F() won't work.朋友声明将F()声明为非成员 function,然后C::F()C().F()都不起作用。 And you have to add a declaration in namespace scope for calling it because it's not visible for name lookup (except ADL , but F() takes no parameters then ADL doesn't work for it).而且您必须在命名空间 scope 中添加一个声明来调用它,因为它对于名称查找不可见(除了ADL ,但F()没有参数,然后 ADL 不起作用)。

A name first declared in a friend declaration within a class or class template X becomes a member of the innermost enclosing namespace of X, but is not visible for lookup (except argument-dependent lookup that considers X) unless a matching declaration at the namespace scope is provided在 class 或 class 模板 X 中的友元声明中首先声明的名称成为 X 的最内层封闭命名空间的成员,但对于查找不可见(除了考虑 X 的参数相关查找),除非命名空间 Z31A11FD140BE4BEFAECD19A 中的匹配声明提供

and

Names introduced by friend declarations within a non-local class X become members of the innermost enclosing namespace of X, but they do not become visible to ordinary name lookup (neither unqualified nor qualified ) unless a matching declaration is provided at namespace scope, either before or after the class definition.由非本地 class X 中的元声明引入的名称成为 X 的最内层封闭命名空间的成员,但它们对普通名称查找不可见( 不合格不合格),除非在命名空间 scope 之前提供匹配声明或在 class 定义之后。 Such name may be found through ADL which considers both namespaces and classes.这样的名称可以通过考虑命名空间和类的ADL找到。

Eg例如

void F();
class C
{
    friend void F() {cout<<"inner friend func"<<endl;}
};

Then call it like然后像这样称呼它

F();

LIVE居住

Declaring the function as a friend does not make it part of the class.将 function 声明为朋友不会使其成为 class 的一部分。 You need to declare it outside:你需要在外面声明它:

#include <iostream>

using std::cout;
using std::endl;

class C
{
    friend void F() {cout<<"inner friend func"<<endl;}
};

void F();

int main() {
    F();
}

Or better, put also the definition outside of the class.或者更好的是,也将定义放在 class 之外。

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

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