重新启动游戏并重新实例化对象
简介
我正在用 C++ 创建一个小游戏,想创建一个重新启动游戏的函数。
首先,我创建对象player
。然后我有一个 if 语句来确定何时按下某个键来调用 New() 方法。
我的目标
在该方法中,我想重新实例化 Player 类的对象,因此所有变量都将被重置。
我的代码:
Player player;
//New game method
Game::New()
{
player = new Player();
}
//Game loop
Game::Loop()
{
if(keyispressed(key))
{
Game.New();
}
}
有什么建议吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您混淆了指针变量和非指针变量。
new Player()
返回动态分配的Player
对象的地址。您不能将此地址分配给非指针变量player
;您需要将player
声明为指针:您还需要记住释放之前使用匹配的
delete
分配的内存:现在
player
> 是一个指针,您必须更新您编写的使用播放器的任何其他代码,才能使用->
成员访问运算符。例如,player.name()
将变为player->name()
You're confusing pointer and non-pointer variables.
new Player()
returns the address of a dynamically allocatedPlayer
object. You cannot assign this address to the non-pointer variableplayer
; you'd need to declareplayer
as a pointer:You also need to remember to release the memory previously allocated with a matching
delete
: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 becomeplayer->name()