-1

I would like to understand aggregation so I tried making a simple test code, but it doesn't work in my compiler, sometimes it works online.

code for main:

#include <iostream>
#include <string>    
#include "player.h"
#include "game.h"
using namespace std;

int main(){ 
    game game;
    game.playGame();

    return 0;
}

code for game.cpp:

#include "game.h"
#include "player.h"

game::game(){
    player.setBalance(0); 
}

void game::playGame(){
  cout << "playing game." ;  //just for debugging
}

code for game.h:

#ifndef GAME  
#define GAME
#include <iostream>
using namespace std;

class game{

  private:
    player player;

  public:
    game();
    void playGame();

}; 


#endif

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

code for player.h:

 #ifndef PLAYER // used on headers 
 #define PLAYER

 class player{

     private:
     int balance;

   public:

     player();
     player(int);
     int getBalance();
     void setBalance(int);
 }; 

 #endif

I think the problem is probably on the headers. the error I get is:

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{
       ^~~~~~
melpomene
  • 84,125
  • 8
  • 85
  • 148

1 Answers1

0

I think that the problem is in class game, because it doesn't know a class player, use forward declaration or just write #include "player.h" in game.h

hashtag
  • 114
  • 4
  • Forward declaration would be the right way, and following [this guidelines](https://stackoverflow.com/questions/625799/resolve-build-errors-due-to-circular-dependency-amongst-classes). – πάντα ῥεῖ May 18 '19 at 20:52