我想了解聚合,所以我尝试编写一个简单的测试代码,但是它在我的编译器中不起作用,有时可以在线运行。
主代码:
#include <iostream>
#include <string>
#include "player.h"
#include "game.h"
using namespace std;
int main(){
game game;
game.playGame();
return 0;
}
game.cpp的代码:
#include "game.h"
#include "player.h"
game::game(){
player.setBalance(0);
}
void game::playGame(){
cout << "playing game." ; //just for debugging
}
game.h的代码:
#ifndef GAME
#define GAME
#include <iostream>
using namespace std;
class game{
private:
player player;
public:
game();
void playGame();
};
#endif
player.cpp的代码:
#include "player.h"
player::player(){
balance = 0;
}
player::player(int theBalance){
balance = theBalance;
}
int player::getBalance(){
return balance;
}
void player::setBalance(int theBalance){
balance = theBalance;
}
player.h的代码:
#ifndef PLAYER // used on headers
#define PLAYER
class player{
private:
int balance;
public:
player();
player(int);
int getBalance();
void setBalance(int);
};
#endif
我认为问题可能出在标题上。 我得到的错误是:
In file included from main.cpp:5:0:
game.h:10:12: error: declaration of 'player game::player' [-fpermissive]
player player;
In file included from main.cpp:4:0:
player.h:5:7: error: changes meaning of 'player' from 'class player' [-fpermissive]
class player{
^~~~~~
答案 0 :(得分:0)
我认为问题出在类游戏中,因为它不认识类玩家,使用前向声明或只是在game.h中写#include "player.h"