来自 class 声明为另一个朋友的方法引发错误

Method from a class declared as friend of another one raises error

我有以下两个 类 PlayerFriendOfPlayer:

Player.hpp

#ifndef PLAYER
#define PLAYER

#include"FriendOfPlayer.hpp"
#include<string>


using namespace std;

//class FriendOfPlayer;

class Player{

    public:

           // getters and setters ...

        static int getNbObj(){
            return nbObj;
        };

        friend void FriendOfPlayer::displayPlayerPrivateMember(Player &p);
        

        // constructor
        Player();
        Player(string name= "None", int health = 0, int xp = 0);
        Player(const Player &source);


        // Destructor
        ~Player(){
            --nbObj;
        };


    private:
        //private members not displayed
        string privMember = "private member";
        static int nbObj;

       
};

#endif

Player.cpp

#include "Player.hpp"
#include<string>

using namespace std;


Player::Player(){;};

Player::Player(string name, int health, int xp)
    : name{name}, health{health}, xp{xp}{
        ++nbObj;
    }

Player::Player(const Player &source)
        : name{"I am a copy"}, health{source.health}, xp{source.xp}{
            ++nbObj;
        }


int Player::nbObj = 0;

FriendOfPlayer.hpp

#ifndef FRIEND_OF_PLAYER
#define FRIEND_OF_PLAYER

#include"Player.hpp"

class FriendOfPlayer {

    public:

        void displayPlayerPrivateMember(Player &p);


};

#endif

FriendOfPlayer.cpp

#include "Player.hpp"
#include "FriendOfPlayer.hpp"


#include<iostream>
#include<stdio.h>


void FriendOfPlayer::displayPlayerPrivateMember(Player &p){

    cout << p.privMember << endl;
}

但是,在编译这段代码时,我得到:

g++ Player.cpp FriendOfPlayer.cpp
FriendOfPlayer.cpp:9:6: error: prototype for ‘void FriendOfPlayer::displayPlayerPrivateMember(Player&)’ does not match any in class ‘FriendOfPlayer’
 void FriendOfPlayer::displayPlayerPrivateMember(Player &p){
      ^~~~~~~~~~~~~~
In file included from Player.hpp:5:0:
FriendOfPlayer.hpp:10:14: error: candidate is: void FriendOfPlayer::displayPlayerPrivateMember(int&)
         void displayPlayerPrivateMember(Player::Player &p);

我做错了什么?原型 void FriendOfPlayer::displayPlayerPrivateMember(int&)从何而来?

我想知道为什么你没有遇到 header 包含问题。你不能像你那样做循环包含。我建议从您的 Friendofplayer.hpp 中删除 #include "player.hpp。相反,只需在 Friendofplayer.hpp.

中转发声明 Player class

编辑:你得到的错误信息令人困惑,但我自己试了一下,循环依赖是错误的原因。前向声明解决了这个问题。尝试最小示例 here.