重新启动游戏并重新启动对象 [英] Restarting a game and reinstantiate objects
问题描述
简介
我在C ++中创建一个小游戏,并且想创建一个函数来重新启动游戏。
首先我创建对象 player
。然后我有一个if语句来确定某个键是否被按下来调用 New()
方法。
我的目标
在该方法中,我想重新展示
<$> p $ p>
玩家;
//新游戏方法
Game :: New()
{
player = new Player();
}
//游戏循环
Game :: Loop()
{
if(keyispressed(key))
{
Game.New();
}
}
有任何建议吗?
你混淆指针和非指针变量。 new Player()
返回动态分配的 Player
对象的地址。您不能将此地址分配给非指针变量 player
;您需要将 player
声明为指针:
player = new Player();
您还需要记住释放先前使用匹配的 delete
:
//播放器开始指向没有
Player * player = 0;
//新游戏方法
Game :: New()
{
//如果玩家已经指向某个内容,释放该内存
if播放器)
删除播放器;
player = new Player();
}
现在玩家
是一个指针,你必须更新任何其他使用player的代码,使用 - >
成员访问操作符。例如, player.name()
将成为 player-> name()
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?
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()
这篇关于重新启动游戏并重新启动对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!