C++ 来自声明为另一个类的朋友的类的方法引发错误
我有以下两个职业C++ 来自声明为另一个类的朋友的类的方法引发错误,c++,friend,C++,Friend,我有以下两个职业Player和FriendOfPlayer: Player.hpp #ifndef PLAYER #define PLAYER #include"FriendOfPlayer.hpp" #include<string> using namespace std; //class FriendOfPlayer; class Player{ public: // getters and setters ...
Player
和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
#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<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;
#include "Player.hpp"
#include "FriendOfPlayer.hpp"
#include<iostream>
#include<stdio.h>
void FriendOfPlayer::displayPlayerPrivateMember(Player &p){
cout << p.privMember << endl;
}
我做错了什么?原型
void FriendOfPlayer::displayerprivatember(int&)
从何而来?我想知道为什么没有标题包含问题。你不能像以前那样做圆形包含。我建议从Friendofplayer.hpp中删除#include“player.hpp
。而只需在Friendofplayer.hpp中向前声明player类
编辑:您收到的错误消息令人困惑,但我只是自己尝试过,循环依赖性是导致错误的原因。转发声明解决了该问题。请尝试最简单的示例。我是否应该始终遵循以下准则:包含在cpp中,并在标题中转发声明?@FLOFL29:仅在需要时,请参阅此处的错误#7:。
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);