Friends are confused

$ 11.4 / 5 - "[...] The friend function defined in the class is in the (lexical) scope of the class in which it is defined [...]"

What does this operator mean?

struct A{ typedef int MYINT; void f2(){f();} // Error, 'f' is undefined friend void f(){MYINT mi = 0;} // Why does this work, shouldn' it be A::MYINT? void f1(){f();} // Error, 'f' is undefined }; int main(){} 
  • What is not clear here is that calling "f" from "A :: f1" is understandable. However, why is the call "f" from "A :: f2" poorly formed when a friend is in the "lexical" range of the friend class? What does the lexical domain mean?

  • In the same type, why is the use of 'MYINT' in 'f' OK? Shouldn't it be "A :: MYINT"?

If I add a parameter like "A *" to "f", then both "f1" and "f2" can find "f" due to ADL. It's clear.

+6
c ++ friend
source share
2 answers

You specified only part of the & sect; 11.4 / 5. Accordingly, f() should first be declared outside the class (the function must have a namespace scope). Try the following:

 void f(); // declare it first struct A{ typedef int MYINT; void f2(){f();} friend void f(){MYINT mi = 0;} // definition of global f, a friend of A void f1(){f();} }; 

Regarding the second question, this is normal due to your quoting of the & sect; 11.4 / 5. f() obeys the same naming rules as a static member function of this class and does not have special access rights to members of the enclosing class.

+1
source share

Here is my interpretation of one part of my request, which

"Why can MYINT" be called "MYINT" instead of "A :: MYINT"?

$ 3.4.1 / 9 states - "Search for a name for the name used in the definition of the friend function (11.4), defined in the line in the class that provides friendship, proceed as described for searching in the definition of member functions. If the friend function is not defined in the class providing friendship, the search for a name in the definition of a friend’s function should act as described for searching in a function of a member of the definition’s namespace. "

In our case, the name to look at is "MYINT", which is an unqualified name. A search for this name inside the friend definition of 'f', which is defined inline in the class, will be performed in the same order as for member functions of 'A'.

Do I understand correctly?

0
source share

All Articles