I have the following two relevant classes in this problem (see below).
When I run this, I get the following erros:
1. Player.cpp:18:5: error: 'World' does not name a type
World w;
^
2. Player.cpp:20:26: error: 'World' has not been declared
Player(int x, int y, World w) {
(and a few more but these are probably caused by the top two).
I don't understand what the problem is. I am trying to pass ''this'' (world object) to the Player object. But if I pass it as ''this'', it will be a copy and not a reference in the first place right? Should I pass it as a reference (if I want to edit the World object from the Player class).
Also, why does it show the top errors? :-s
This can't work, because any Player contains a World, and each World contains a Player, which each contains a World, and so on. Somewhere you're going to want to use a pointer or something.
If I want the Player object to have a pointer to the world which owns it, I have to make another class that passed the World object (reference) inside Player right? Because I won't be able to do so with 2 (World, Player) classes?
You do not need a third class. The World class can give its owned Player a pointer to itself (that's what the this pointer is for):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
// player.h
class World; // <- forward declare the World class
class Player {
public:
int x;
int y;
World* w; // <- pointer
Player(int x, int y, World* w) { // <- pointer
this->x = x;
this->w=w;
this->y = y;
}
//...
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
// world.h
#include "player.h"
class Tile;
class World {
private:
public:
Tile *t[9][9];
Player p;
int counter;
World()
: p( player_x, player_y, this ) // <- give the owned player a pointer to 'this'
{
}