0

我有从类Ball派生的PhysicsObject类。在以下方法中,我从指针获取Ball实例并检查其是否为 type 。当我调用该方法时,它不会在类对象中被调用。我在这里做错了什么?voidPhysicsObjectcollidingWithBall

更新 我在底部添加了一个sscce 。请参考。

代码

void Levels::BeginContact(b2Contact *contact) {
    b2Fixture *fixtureA = contact->GetFixtureA();
    b2Fixture *fixtureB = contact->GetFixtureB();
    void *objA = fixtureA->GetUserData();
    void *objB = fixtureB->GetUserData();

    PhysicsObject* physicsObjA = reinterpret_cast<PhysicsObject*>(objA);
    PhysicsObject* physicsObjB = reinterpret_cast<PhysicsObject*>(objB);
    if ((physicsObjA != 0) && (physicsObjB != 0)) {
        physicsObjA->collidingWith(physicsObjB);    //not working
        physicsObjB->collidingWith(physicsObjA);
    }
}

物理对象

#ifndef PHYSICSOBJECT_H_
#define PHYSICSOBJECT_H_

class PhysicsObject {
public:
    PhysicsObject();
    virtual ~PhysicsObject();

    virtual void collidingWith(PhysicsObject *obj) = 0;
};

#endif /* PHYSICSOBJECT_H_ */

球.h

#ifndef BALL_H_
#define BALL_H_

#include "Box2D/Box2d.h"
#include "cocos2d.h"
#include "PhysicsObject.h"

class Ball : public PhysicsObject {
public:
    //other methods
    void collidingWith(PhysicsObject *obj);
};

#endif /* BALL_H_ */

球.cpp

void Ball::collidingWith(PhysicsObject *obj) {
    CCLOG("Ball::collidingWith"); //this method is not being called
}
 //other methods

Ball::Ball() {
    //other code
    b2FixtureDef ballShapeDef;
    ballShapeDef.userData = this;
    //other code
}

更新 我有 3-4 个其他类,它们是从PhysicsObject类似Ball的,我在这里没有提到的,但公共代码是相同的。

UPDATE SSCCE
In出现错误main.cppfoo()baseObjA->collidingWith(baseObjA);

基类

class Base
{
public:
    Base(void);
    virtual ~Base(void);
    virtual void collidingWith(Base *obj) = 0;
};

另一个基类

class AnotherBase
{
public:
    AnotherBase(void);
    ~AnotherBase(void);
    virtual void foo();
};

派生类头

#include "Base.h"
#include "AnotherBase.h"
class Derived :
    public AnotherBase, Base
{
public:
    Derived(void);
    ~Derived(void);
    void collidingWith(Base *obj);
};

派生类实现

#include "Derived.h"

void Derived::collidingWith(Base *obj) {
    printf("Ball::collidingWith");
}

主文件

#include "Derived.h"

void myFoo(void* userData);
int _tmain(int argc, _TCHAR* argv[])
{
    Derived *derived = new Derived();
    void* userData = derived;
    myFoo(userData);
    return 0;
}

void myFoo(void* userData) 
{
    Base* baseObjA = reinterpret_cast<Base*>(userData); 
    if (baseObjA != 0) {
        baseObjA->collidingWith(baseObjA);// Error here
    }
}
4

1 回答 1

0

从 box2d 中的 void* 进行投射也给了我非常相似的问题。

似乎是reinterpret_cast导致错误的原因,collidingWith虚拟方法也是如此。(如果该方法不是虚拟的,您应该可以毫无问题地调用它)。

我已经解决了这个问题:

void* data; // You know it's type is Base

Base* base = static_cast<Base*>(data);
Derived* derived = dynamic_cast<Derived*>(base);

derived->collidingWith();
于 2013-05-12T17:31:50.273 回答