dimanche 18 mars 2018

(C++) Pointers to Pointers of objects in different classes

everyone. I'm working on a final project for school and it's coming along great, but I've run into a bit of a problem with trying to use a pointer to a pointer. I'll do my best to explain the problem below:

So I have a class called Player that sort of looks like this:

class Player
{
    Player();
    int health;
    void adjustHealth(int);
};

Player::Player()
{
    health = 40;
}

void Player::adjustHealth(int adjust)
{
    health += adjust;
}

I have another class called Shelter, that include "Player.h" and looks a little like this:

class Shelter
{
    Shelter();
    Player* player;     // Create a pointer to Player class.
};

In the Shelter header file, I have the following in my default constructor:

Shelter::Shelter()
{
    ...Other code here.
    player = new Player();
}

In the Shelter header file, I use this new player for things like:

 player->adjustHealth(-1);  // Subtract one health from the player.

Which works great.

The problem I'm facing is with creating another class called Church, that is in a separate header file and acts as a separate location in the game. I want Church to use the same player that Shelter does, so it has all of the same stats, etc, rather than creating a new player in Church (which is what I did in Shelter.h).

Right now, I have something like:

class Church
{
Church();
Shelter **cplayer; // This is supposed to be the pointer to the pointer.
};

The default constructor is where I'm having my problem. I want to use the same player from Shelter, not create a new player like I did in Shelter.

Church::Church
{
    What should I do here?
}

I've tried a number of things, but I can't quite get it working. Eventually I want to be able to do something like this:

   player->adjustHealth(-1);    // Subtract one health from the player. 

Only in Church, so that player's stats, like health, are adjusted no matter which location they are in.

I hope my question makes sense. If not, I can try to clarify better. Anyway, thanks in advance.

Aucun commentaire:

Enregistrer un commentaire