访问类中定义的友元函数
有这样的代码:
#include <iostream>
class A{
public:
friend void fun(A a){std::cout << "Im here" << std::endl;}
friend void fun2(){ std::cout << "Im here2" << std::endl; }
friend void fun3();
};
void fun3(){
std::cout << "Im here3" << std::endl;
}
int main()
{
fun(A()); // works ok
//fun2(); error: 'fun2' was not declared in this scope
//A::fun2(); error: 'fun2' is not a member of 'A'
fun3(); // works ok
}
How to access function fun2()?
There is such code:
#include <iostream>
class A{
public:
friend void fun(A a){std::cout << "Im here" << std::endl;}
friend void fun2(){ std::cout << "Im here2" << std::endl; }
friend void fun3();
};
void fun3(){
std::cout << "Im here3" << std::endl;
}
int main()
{
fun(A()); // works ok
//fun2(); error: 'fun2' was not declared in this scope
//A::fun2(); error: 'fun2' is not a member of 'A'
fun3(); // works ok
}
How to access function fun2()?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
尽管您对
fun2
的定义确实定义了一个“全局”函数而不是成员,并使其成为A
的friend
code> 同时,您仍然缺少全局范围本身中同一函数的声明。这意味着该范围内的任何代码都不知道
fun2
存在。fun
也会出现同样的问题,只不过参数相关查找可以接管并查找该函数,因为有一个A
类型的参数。我建议您以通常的方式定义您的函数:
现在请注意,一切都可以工作(除了
fun3
因为我从未定义过它)。Although your definition of
fun2
does define a "global" function rather than a member, and makes it afriend
ofA
at the same time, you are still missing a declaration of the same function in the global scope itself.That means that no code in that scope has any idea that
fun2
exists.The same problem occurs for
fun
, except that Argument-Dependent Lookup can take over and find the function, because there is an argument of typeA
.I recommend instead defining your functions in the usual manner:
Notice now that everything works (except
fun3
because I never defined it).您可以调用
fun
的原因是类A
内的友元声明使其仅通过参数相关查找可见。否则,友元声明不会使它们声明的函数在出现的类范围之外自动可见。您需要在命名空间范围或
main
内部添加声明,以使fun2
在main
中可见。例如,
fun3
在main
内部可见,因为它的定义(在类外部)也是一个声明,使其在main
中可见。ISO/IEC 14882:2011 7.3.1.2:
3.4.2(依赖于参数的名称查找)/4:
The reason that you can call
fun
is that the friend declaration inside classA
makes it visible via argument dependent lookup only. Otherwise friend declarations don't make the functions that they declare automatically visible outside of the class scope where the appear.You need to add a declaration at namespace scope or inside
main
to makefun2
visible inmain
.E.g.
fun3
is visible insidemain
because its definition (outside of the class) is also a declaration that makes it visible frommain
.ISO/IEC 14882:2011 7.3.1.2:
3.4.2 (Argument-dependent name lookup) / 4: