简体   繁体   中英

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

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM