重新启动游戏并重新实例化对象

发布于 2024-10-30 07:56:02 字数 456 浏览 1 评论 0原文

简介

我正在用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

累赘 2024-11-06 07:56:02

您混淆了指针变量和非指针变量。 new Player() 返回动态分配的 Player 对象的地址。您不能将此地址分配给非指针变量player;您需要将 player 声明为指针:

Player* player = new Player();

您还需要记住释放之前使用匹配的 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();
}

现在 player > 是一个指针,您必须更新您编写的使用播放器的任何其他代码,才能使用 -> 成员访问运算符。例如,player.name() 将变为 player->name()

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()

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文