Domanda

This is a very similar problem to a question i have already looked at, answered here - Restarting a game and reinstantiate objects .

I want exactly the same thing except my problem is slightly different in that the object i wish to reinstantiate is 'global' and is only ever created when the program first runs.

At present i create the new 'Player' after my #includes and before my function prototypes ...

#include "Player.h"
#include "Monster.h"

using namespace std;

string MonsterTypes[3] = {"Orc","Goblin","Dark Rider"};
//create a stack of 'monsters'
stack<Monster>MonsterList;

Player* NewPlayer = new Player();

int NewGame();
void SetupPlayer();
void SetupMonsters();
void MainGame();
void Combat();
int GetMonstersLeft();

Do i need to create an entire factory class just to create a single player? Obviously when i call the function 'setupPlayer' i could create the player object in there, but would i not then have to pass 'NewPlayer' to every other function, i was just wandering if there was a way to avoid doing that?

È stato utile?

Soluzione

You can create a new player in SetupPlayer, and assign it to NewPlayer.

Since your global NewPlayer is a pointer to a Player object, you can simply create a new Player in its place every time you call SetupPlayer(), as follows:

Player* NewPlayer = NULL;  // Initialized when calling SetupPlayer()

void SetupPlayer() {
    delete NewPlayer;  // Delete the previous player (if any)
    NewPlayer = new Player();
}

Altri suggerimenti

You don't really need dynamic allocation. You can just declare an automatic variable like this:

Player player;

and then when you want to reset it you can use:

player = Player();

Always remember that dynamic allocation is expensive.


What I would probably do, instead, is to create a "factory" function:

Player make_player() {
    Player ret;
    // setup ret
    return ret;
}

So that you can get rid of that global object. Don't worry about the performance of copying the object back when returning: copies are elided by a well-known optimization (return value optimization - RVO).

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top