I'm having a situation similar to the one described in Specify a class member function as a friend of another class?.
However in my case, class B needs to know class A since it's using it, so the solution given in that thread is not working for me. I tried to give also a forward declaration to the function itself but it didn't work as well. It seems that each class need the full definition of the other...
Is there any easy way to solve it? I prefer a solution which doesn't involve new classes which wrap one of the old classes.
code example:
//A.h
class B; //not helping
void B::fB(); //not helping
class A
{
public:
friend void B::fB();
void fA(){};
protected:
void fA_protected(){};
};
//B.h
#include "A.h"
class B
{
private:
A a;
public:
void fB(){ a.fA_protected();} // this function should call the protected function
void fB2(){ a.fA(); }
};
Thanks for the helpers!
(By the way this my first question, I hope I explain myself clearly)
If you can change B to take a pointer on A, following may help: (I use raw pointer as you can't use smart pointer according to comment).
//A.h
#include "B.h"
class A
{
public:
friend void B::fB();
void fA() {};
protected:
void fA_protected(){};
};
//B.h
class A; // forward declaration
class B
{
private:
A* a;
public:
B();
~B(); // rule of 3
B(const B& b); // rule of 3
B& operator = (const B&); // rule of 3
void fB(); // this function should call the protected function
void fB2();
};
//B.cpp
#include "B.h"
#include "A.h"
B::B() : a(new A) {}
B::~B() { delete a; } // rule of 3
B::B(const B& b) : a(new A(*b.a)) {} // rule of 3
B& B::operator = (const B&) { *a = *b.a; return *this; } // rule of 3
void B::fB() { a->fA_protected();}
void B::fB2() { a->fA(); }
来源:https://stackoverflow.com/questions/21850292/friend-member-function-in-c-forward-declaration-not-working