gpt4 book ai didi

c++ - 在 C++ 中使用多重继承时 ESP 无效 (VS2005)

转载 作者:搜寻专家 更新时间:2023-10-30 23:50:22 25 4
gpt4 key购买 nike

我一直在制作一款使用 Box2D 物理引擎的游戏,我发现堆栈指针 (ESP) 和多重继承有些奇怪。我设法用最少的代码重现了它,而且我声明要在多重继承中使用的类的顺序似乎决定了程序是否崩溃。

#include <iostream>
#include <string.h>

using namespace std;

class IPhysicsObject
{
public:
virtual void Collide(IPhysicsObject *other, float angle, int pos)=0;
};

class IBoardFeature
{
public:
IBoardFeature(){};
~IBoardFeature(){};

virtual bool OnAttach(int x){ return true; }
virtual bool Update(int x, float dt)=0;
};

/*
class CScorezone : public IBoardFeature, public IPhysicsObject // this breaks !!!
class CScorezone : public IPhysicsObject, public IBoardFeature // this works !!!
*/
class CScorezone : public IBoardFeature, public IPhysicsObject
{
public:
CScorezone(){}
~CScorezone(void){}

virtual bool Update(int x, float dt)
{
return true;
}

virtual void Collide(IPhysicsObject *other, float angle, int pos)
{
}

virtual bool OnAttach(int x){ return true; }
};


int main(int argc, char *argv[])
{
CScorezone *scoreZone = new CScorezone();
CScorezone *otherZone = new CScorezone();

void *voidZone = scoreZone;
IPhysicsObject *physZone = static_cast<IPhysicsObject*>(voidZone);
physZone->Collide(otherZone, 10, 1);

delete scoreZone;
delete otherZone;

// wait for user input
int x;
cin >> x;
return 0;
}

在 Debug模式下运行会导致以下错误

Run-Time Check Failure #0 - The value of ESP was not properly saved across a function call. This is usually a result of calling a function declared with one calling convention with a function pointer declared with a different calling convention.

当我进入以下代码行时:

physZone->Collide(otherZone, 10, 1);

我注意到它进入了 CScoreZone::OnAttach,而不是 CScoreZone::Collide。为什么是这样?当我更改 CScoreZone 的继承顺序时,它工作正常

class CScorezone : public IPhysicsObject, public IBoardFeature

我在 Windows XP 上运行 VS2005 SP2 (8.0.50727.768)。有什么想法吗?

最佳答案

您不必将 CScorezone* 分配给 void*,然后将其转换为 IPhysicsObject*。因为 CScorezone is-a IPhysicsObject 你可以简单地分配给基指针:

    IPhysicsObject *scoreZone = new CScorezone();
IPhysicsObject *otherZone = new CScorezone();

您还缺少 IPhysicsObject 声明中的公共(public)虚拟析构函数。

编辑:

我是你在评论中描述的回调情况(通过一些 C api?)我会使用简单的 struct 和指向多态类型的指针来避免未定义的强制转换,比如:

    // one more level of indirection
struct cb_data
{
IPhysicsObject* target;
};

// callback function
int callback( void* data )
{
const cb_data& cbd( *static_cast<cb_data*>( data ));

return cbd.target->Collide( ... );
}

关于c++ - 在 C++ 中使用多重继承时 ESP 无效 (VS2005),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2125476/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com