C++ how to use key word 'friend' with member functions from two classes contain with each other

304 views Asked by At

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?

1

There are 1 answers

2
rdowell On

Your problem is here:

class FriendVisitor;
class FriendTest{
    friend int FriendVisitor::getTestAdd();

At this point in the compilation, the FriendTest class knows about the existence of the FriendVisitor class, but not any of its members, as its declaration is not complete. If you reorder your code to fully declare FriendVisitor first, then its declaration is complete once you declare the friend function in FriendTest and it compiles:

#include <stdio.h>
class FriendTest; // Forward declaration
class FriendVisitor{
    FriendTest* test; // Only references the class, so only forward declaration needed
public:
    FriendVisitor(){

    }
    int getTestAdd();
};

class FriendTest{
    friend int FriendVisitor::getTestAdd();  // FriendVisitor is fully declared, friend function is legal
private:
    int add=23;
    int  getAdd(){
        return add;
    }
public:
    void test(){
        printf("hello");
    }
    FriendTest()=default;
};