Currently I am reading a book about C++
and it has some exercises. One of the exercises asks to build two classes where each has a friend method for another. My current guess looks like this:
#include <iostream>
using std::cout;
using std::endl;
class Y;
class X{
public:
void friend Y::f(X* x);
void g(Y* y){cout << "inside g(Y*)" << endl;}
};
class Y{
public:
void friend X::g(Y* y);
void f(X* x) {cout << "inside f(X*)" << endl;}
};
But my guess does not compile because class X
have void friend Y::f(X* x);
method declaration. How can I solve the puzzle? Give me some more guesses, please.
In order to declare a function as a friend, the compiler has to have seen it first, and C++ does not allow forward declarations of member functions. Therefore what you are trying to do is not possible in the way you want. You could try using the "passkey" method from here.
Alternatively, you could replace void friend Y::f(X* x);
with friend class Y;
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With