[英]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;
}
}
注意事项:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.