Two classes with other methods in C ++

I am currently reading a book on C++ , and it has some exercises. In one of the exercises, it is proposed to build two classes, where each of them has a friend method for the other. My current hunch 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 hunch is not compiled, because class X has a declaration of the void friend Y::f(X* x); method void friend Y::f(X* x); . How can I solve the puzzle? Give me some more guesses, please.

+4
source share
1 answer

To declare a function as a friend, the compiler should have seen it first, and C ++ does not allow forwarding declarations of member functions. Therefore, what you are trying to do is not possible in the way you want. You can try using the "passkey" method from here .

Alternatively, you can replace void friend Y::f(X* x); on friend class Y; .

+4
source

Source: https://habr.com/ru/post/1486694/


All Articles