为什么此节点列表无法正常工作?

时间:2013-06-24 18:27:16

标签: c++ list

为什么,虽然我已经添加了4个GameObjects,但在GameLoop中,Console只给出了一次“GameObject Update”和“GameObject Render”?

另一个Qustion,我如何为GameObjects制作自毁函数?

最后一个问题,最好的方法是什么,GameObject可以与列表中的其他游戏对象进行通信?

#include <iostream>
using namespace std;

class GameObject
{
public:
    GameObject *nextGameObject;

    GameObject()
    {
        cout<<"GameObject Constructor!\n";
        nextGameObject = nullptr;
    }
    ~GameObject()
    {
        cout<<"GameObject Destructor\n";
        if(nextGameObject != nullptr)
        {
            delete nextGameObject;
        }
    }

    virtual void Update()
    {
        cout<<"GameObject Update!\n";
    }
    virtual void Render()
    {
        cout<<"GameObject Render!\n";
    }
};

class GameObjectManager
{
private:
    GameObject *firstGameObject;
public:
    GameObjectManager()
    {
        firstGameObject = nullptr;
    }
    ~GameObjectManager()
    {
        if(firstGameObject != nullptr)
        {
            delete firstGameObject;
        }
    }

    void Update()
    {
        if(firstGameObject != nullptr)
        {
            GameObject *helpGameObject = firstGameObject;
            while(helpGameObject != nullptr)
            {
                helpGameObject->Update();
                helpGameObject = helpGameObject->nextGameObject;
            }
        }
    }
    void Render()
    {
        if(firstGameObject != nullptr)
        {
            GameObject *helpGameObject = firstGameObject;
            while(helpGameObject != nullptr)
            {
                helpGameObject->Render();
                helpGameObject = helpGameObject->nextGameObject;
            }
        }
    }

    void Add(GameObject *newGameObject)
    {
        if(firstGameObject == nullptr)
        {
            firstGameObject = newGameObject;
        }
        else
        {
            GameObject *helpGameObject = firstGameObject;
            while(helpGameObject != nullptr)
            {
                helpGameObject = helpGameObject->nextGameObject;
            }
            helpGameObject = newGameObject;
        }
    }
};

int main()
{
    GameObjectManager gom;
    bool run = true;

    gom.Add(new GameObject);
    gom.Add(new GameObject);
    gom.Add(new GameObject);
    gom.Add(new GameObject);

    while(run)
    {
        cout<<"GameLoop Start\n";
        gom.Update();
        gom.Render();
        cout<<"GameLoop End\n";
        cin.get();
    }

    return 0;
}

2 个答案:

答案 0 :(得分:0)

对于链表来说,这是一个可怕的解决方案,但我会回答你的问题。故障在Add()中。在这里,您只需修改局部变量helpGameObject。相反,您应该停在没有后继的对象并修改该对象nextGameObject。

答案 1 :(得分:0)

问题在于您的Add功能。

以下行:

helpGameObject = newGameObject;

实际上并没有改变helpGameObject指向的值,而是更改指针本身。

我认为最好的解决方案是将其更改为以下

        GameObject *helpGameObject = firstGameObject;
        while(helpGameObject->nextGameObject != nullptr)
        {
            helpGameObject = helpGameObject->nextGameObject;
        }
        helpGameObject->nextGameObject = newGameObject;