我非常链接列表的新内容,我似乎无法弄清楚为什么这不起作用。
程序没有崩溃,编译器没有显示任何错误,但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;
}
}
}
答案 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;
}
}
注意事项: