简体   繁体   中英

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

I have the following two classes Player and FriendOfPlayer :

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

However, when compiling this code, I get:

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

What am I doing wrong? Where can the prototype void FriendOfPlayer::displayPlayerPrivateMember(int&) come from?

I wonder why you don't get an header inclusion problem. You can't do a circular inclusion like you did. I would suggest to remove #include "player.hpp from your Friendofplayer.hpp. Instead just forward declare the Player class in Friendofplayer.hpp.

Edit: The error message you got is confusing, but I just tried it by myself and the cyclic dependency was the reason for the error. Forward declaration solved that problem. Try minimum example here .

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