Home c++ C++ friend function and namespace

C++ friend function and namespace

Author

Date

Category

file.cpp

# include "file.h"
namespace NS
{
 void f (const A & amp; obj)
 {
  std :: cout & lt; & lt; obj.data;
 }
}

file.h

class A
{
 private: int data;
 friend void NS :: f (const A & amp; obj);
}

The compiler swears at this. If you describe NS in file.cpp before class A, then everything works. Can you please tell me what I don’t understand? Why it happens? How do I make it work when NS is in another file?

UPD: and in the same file does not work. “Use of undefined type A”


Answer 1, authority 100%

This is fixed like this:

file.cpp remains unchanged.

file.h says this:

class A;
namespace NS
{
  void f (const A & amp; obj);
}
class A
{
 private:
  int data;
  friend void NS :: f (const A & amp; obj);
}

Why didn’t your option work?

First, the compiler did not know what NS is: a namespace or a class, or something else.

However, even if you add namespace NS {} above the class, it will still not work, but this time the error will be different: error: 'void NS :: f (const A & amp; ) 'should have been declared inside' NS '(c) GCC.

If f were in the same namespace as the class, friend void f (const A & amp;); would have worked without a function declaration. (This line would itself be a function declaration, although it could only be accessed through an argument-dependent lookup to a normal (re) declaration.)

Why is that? Apparently the developers of the standard decided that it is overkill to declare functions in arbitrary namespaces from classes in other namespaces.


Answer 2, authority 60%

Friendship with a function can only be used if the function is declared in advance. You can declare a function, but you need to declare a class in advance. It doesn’t matter in which file you do it, the main thing is order.

# include & lt; iostream & gt;
class A;
namespace NS {
void f (const A & amp; obj); }
class A
{
 private: int data;
 friend void NS :: f (const A & amp; obj);
};
namespace NS {
 void f (const A & amp; obj) {
  std :: cout & lt; & lt; obj.data; }}

Answer 3, authority 60%

In C++, qualified names like NS :: f are used only to refer to previously declared ones, i.e. entities already known to the compiler. If you want to use a qualified name – make sure that the entity that this name refers to is declared in advance. To put it simply, such entities should be declared higher in the file.

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions