[英]Method from a class declared as friend of another one raises error
我有以下兩個類Player
和FriendOfPlayer
:
播放器.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
播放器.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;
玩家之友.hpp
#ifndef FRIEND_OF_PLAYER
#define FRIEND_OF_PLAYER
#include"Player.hpp"
class FriendOfPlayer {
public:
void displayPlayerPrivateMember(Player &p);
};
#endif
玩家之友.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&)
來自哪里?
我想知道為什么您沒有遇到標題包含問題。 你不能像你那樣做一個循環包含。 我建議從您的 Friendofplayer.hpp 中刪除#include "player.hpp
。而只是在 Friendofplayer.hpp 中向前聲明 Player 類。
編輯:您收到的錯誤消息令人困惑,但我只是自己嘗試過,循環依賴是導致錯誤的原因。 前向聲明解決了這個問題。 在此處嘗試最小示例。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.