如何才能使此链接列表正常工作?

时间:2012-11-07 15:07:48

标签: c++ linked-list

非常链接列表的新内容,我似乎无法弄清楚为什么这不起作用。

程序没有崩溃,编译器没有显示任何错误,但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;
        }
    }
}

2 个答案:

答案 0 :(得分:1)

如果类型为clsParent或其子类,则为pCurrent。键入clsPlayer的dynamic_cast将始终失败并返回null。 也许有成员数据,你应该使用类似的东西(甚至可能没有必要):

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

答案 1 :(得分:0)

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

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&amp; 1的结果2,注意到遍历列表并调用doActions方法的循环已经简化,因为我们现在避免使用强制转换。
相关问题