gpt4 book ai didi

c++ - 如何在C++中使用/访问类的内部 friend 功能?

转载 作者:行者123 更新时间:2023-12-01 14:39:11 25 4
gpt4 key购买 nike

我们可以在类内声明并定义一个 friend 函数,如下所示

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

如何访问/使用此内部 friend 功能?
C::F() //error: 'F' is not a member of 'C'
C().F()//error: 'class C' has no member named 'F'

最佳答案

friend decalration声明F()为非成员函数,因此C::F()C().F()均不起作用。而且,您必须在命名空间范围内添加一个声明以进行调用,因为在名称查找中该声明不可见(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





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. Such name may be found through ADL which considers both namespaces and classes.



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

然后像这样称呼它
F();

LIVE

关于c++ - 如何在C++中使用/访问类的内部 friend 功能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62445982/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com