Restarting a game and reinstantiate objects

荒凉一梦 提交于 2019-12-09 03:41:13

问题


Introduction

I am creating a small game in C++ and would like to create a function to restart the game.

First I am creating the object player. Then I have an if statement to determine when a certain key is pressed to call the New() method.

My goal

In that method I would like to reinstantiate an object of the Player class, so all variables will be resetted.

My code:

Player player;

//New game method
Game::New()
{
    player = new Player();
}

//Game loop
Game::Loop()
{
    if(keyispressed(key))
    {
        Game.New();
    }
}

Any suggestions?


回答1:


You're confusing pointer and non-pointer variables. new Player() returns the address of a dynamically allocated Player object. You cannot assign this address to the non-pointer variable player; you'd need to declare player as a pointer:

Player* player = new Player();

You also need to remember to release the memory previously allocated with a matching delete:

// player starts out pointing to nothing
Player* player = 0;

//New game method
Game::New()
{
    // If player already points to something, release that memory
    if (player)
        delete player;

    player = new Player();
}

Now that player is a pointer you'll have to update any other code you've written which uses player, to use the -> member access operator. For example, player.name() will become player->name()



来源:https://stackoverflow.com/questions/5552796/restarting-a-game-and-reinstantiate-objects

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!