I'm new learning c++ How do I use friend with member functions from two classes contain with each other? I could not find a good answer through Google
Below is my code:
#ifndef FriendTest_hpp
#define FriendTest_hpp
class FriendVisitor;
class FriendTest{
friend int FriendVisitor::getTestAdd();
private:
int add=23;
int getAdd(){
return add;
}
public:
void test(){
printf("hello");
}
FriendTest()=default;
};
#ifndef FriendVisitor_hpp
#define FriendVisitor_hpp
#include <stdio.h>
class FriendTest;
class FriendVisitor{
FriendTest* test;
public:
FriendVisitor(){
}
int getTestAdd();
};
#endif /* FriendVisitor_hpp */
the IDE gives me the wrong error is :
incomplete type 'FriendVisitor named in nested name specifier'
What is the solution?
Your problem is here:
At this point in the compilation, the
FriendTestclass knows about the existence of theFriendVisitorclass, but not any of its members, as its declaration is not complete. If you reorder your code to fully declareFriendVisitorfirst, then its declaration is complete once you declare the friend function inFriendTestand it compiles: