简体   繁体   中英

How to friend a function inside a namespace which is in a different file?

I'm having an issue with a friend function. Basically I have a class in a header (inside a namespace), which contains a friend function:

namespace X {
class Foo {
// private members
  friend void SomeNamespace::someFunction(const Foo& foo);
}

And in a separate header, I have the function which I'm trying to make a friend, which is inside a namespace:

#include "classHeader.h"
namespace SomeNamespace {
  void someFunction(const X::Foo& foo);
}

This doesn't seem to work, as someFunction can't access Foo's private members, apparently. After some research I found out that I was missing a forward declaration, so I tried adding it:

namespace X{class Foo}; // Forward declare class
void SomeFunction(const X::Foo& foo);

But this does not seem to work either. What's wrong?

To expand on my comments, lets say you have the following three files:

  • Foo header file

    #include "SomeNamespace.h" namespace X { class Foo { friend void SomeNamespace::SomeFunction(const Foo&); }; }
  • SomeNamespace header file

    namespace X { // Forward declaration class Foo; } namespace SomeNamespace { void SomeFunction(const Foo&); }
  • SomeNamespace source file

    #include "SomeNamespace.h" #include "Foo.h" void SomeNamespace::SomeFunction(const Foo& foo) { }

[Note: Things like actual contents, as well as header include guards, purposefully omitted for brevity]

One of the header files needs to use forward declaration only , while the other can use #include .

The important part is that you must include all needed header files in the source file where you define (implement) the classes and functions.

Here's one way:

s.hpp

#pragma once

class Foo; // forward declaration is enough here since you only use a reference

namespace SomeNamespace {
  void someFunction(const Foo& foo);
}

f.hpp

#pragma once
#include "s.hpp"  // the function declaration of someFunction is needed

class Foo {
public:
    Foo(int X);
    friend void SomeNamespace::someFunction(const Foo& foo);
private:
    int x;
};

s.cpp

#include "f.hpp"  // Foo's definition is needed here
#include "s.hpp"
#include <iostream>
namespace SomeNamespace {
  void someFunction(const Foo& foo) {
      std::cout << foo.x << '\n';     // private member now accessible
  }
}

f.cpp

#include "f.hpp"

Foo::Foo(int X) : x(X) {}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM