We can declare and define a friend function inside a class, like below
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. 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).
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
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. Such name may be found through ADL which considers both namespaces and classes.
Eg
void F();
class C
{
friend void F() {cout<<"inner friend func"<<endl;}
};
Then call it like
F();
Declaring the function as a friend does not make it part of the 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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.