What area does a function defined in a class belong to?

class A { friend void f() {} }; // void f() {} // compile error: redifinition of 'void f()' int main() { f(); // compile error: 'f' is not declared in this scope } 

As you can see in the above example, if f is called in A , spanning the namespace region, the compiler simply cannot find f , which gives me an idea that f not in this volume. But when a function definition with the same signature is added, the compiler throws a function override error, which gives me the opposite idea that f really in this area.

So, I am puzzled by what area the function defined in the class belongs to.

+5
source share
2 answers

This is in the namespace containing the class.

However, if it is declared only in a class, then it is available only for a search dependent on the argument. So this will work with the argument type A finding f in the surrounding namespace:

 class A { friend void f(A) {} }; int main() { f(A()); // OK: uses ADL ::f(A()); // Error: doesn't use ADL, and can't find the name without it } 

This is often used for overloaded statements that can only be found by ADLs.

Your version will work if you have declared, but not redefined, a function in the namespace area.

 void f(); 
+6
source

The friend function must be declared, not defined in the class. For instance. friend void f ();

-3
source

All Articles