【发布时间】:2019-05-18 20:41:59
【问题描述】:
我想了解聚合,所以我尝试编写一个简单的测试代码,但它在我的编译器中不起作用,有时它可以在线运行。
主代码:
#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{
^~~~~~
【问题讨论】:
-
您不应将成员命名为与其类类型相同的名称。一些编译器不能很好地处理这个。
-
很好,将错误减少到只有一个错误,即 main.cpp:5:0 处的第一个错误