문제

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;.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top