繁体   English   中英

我怎样才能让这个链表正常工作?

[英]How can i get this Linked List to work properly?

我对链表陌生,我似乎无法弄清楚为什么这不起作用。

程序不会崩溃,编译器也没有显示错误,但doActions()永远不会运行。

这是函数的代码,它在主循环中被调用。

void Action()
{
    clsParent* pCurrent;
    pCurrent = pHead;
    while(pCurrent != NULL)
    {
        clsPlayer* pPlayer;
        pPlayer = dynamic_cast<clsPlayer*>(pCurrent);
        if(pPlayer != NULL)
        {
            pPlayer->doActions();
        }
        pCurrent = pCurrent->pNext;
    }
}

这应该为列表中的每个玩家调用doActions() (尽管只有一个)。

在我尝试将链表实现到代码中之前, doAction()工作得非常好,所以我知道不是这样。 对于那些对其功能感到好奇的人,它会检查玩家是否在跳跃并相应地移动玩家。

编辑:我注意到我可以把其他功能放进去,它会工作

这有效:

void clsPlayer::jump()
{
    if(onGround)
    {
        jumping = true;
        yPos -= gravitySpeed;
        animationState = 3;
    }
}

虽然这不

void clsPlayer::doActions()
{
    if(!onGround)
    {
        yPos += gravitySpeed;
    }

    if(jumping)
    {
        jumpTimeCounter++;
        yPos -= 20;
        if(jumpTimeCounter > 10)
        {
            jumping = false;
            jumpTimeCounter = 0;
        }
    }
}

pCurrent 如果是 clsParent 类型或其子类。 输入 clsPlayer 的 dynamic_cast 将始终失败并返回 null。 也许有一个成员数据,你应该使用类似的东西(甚至可能不需要演员表):

clsPlayer* pPlayer;
pPlayer = dynamic_cast<clsPlayer*>(pCurrent->data);

根据您发布的代码,我将为您提供以下建议的解决方案:

template<T>
class ListNode
{
public:
    T* m_pNext;
};

class Base : public ListNode<Base>
{
public:
    Base();
    virtual ~Base();
    virtual void doActions() = 0;
};

class Derived1 : public Base
{
public:
    Derived1();
    virtual ~Derived1();
    virtual void doActions();
};

class Derived2 : public Base
{
public:
    Derived2();
    virtual ~Derived2();
    virtual void doActions();
};

void action()
{
    Base* pCurrent = pHead;
    while (pCurrent != NULL)
    {
        pCurrent->doActions();
        pCurrent = pCurrent->m_pNext;
    }
}

注意事项:

  1. ListNode 是一个模板类,您的基类(在您的示例中为 clsParent)继承自它。
  2. 基类将 doActions 声明为纯虚函数,以便派生类可以定义自己的特定实现。
  3. 作为 1 和 2 的结果,请注意遍历列表并调用 doActions 方法的循环被简化了,因为我们现在避免了强制转换。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM