在对基类进行类型转换后无法调用方法

时间:2013-04-19 12:01:08

标签: c++ inheritance casting box2d cocos2d-x

我有Ball类派生自PhysicsObject类。在以下方法中,我从Ball指针获取void实例,并检查其类型PhysicsObject是否为collidingWith。当我调用Ball方法时,它不会在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); } } 类对象中调用。我在这里做错了什么?

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

CODE

#ifndef PHYSICSOBJECT_H_
#define PHYSICSOBJECT_H_

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

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

#endif /* PHYSICSOBJECT_H_ */

PHYSICSOBJECT

#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_ */

Ball.h

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
}

Ball.cpp

PhysicsObject

更新 我有另外3-4个来自Ball的类,就像main.cpp一样,我在这里没有提到,但是公共代码是相同的。

更新SSCCE
foo()的{​​{1}} baseObjA->collidingWith(baseObjA);获取错误{/ 1}}

基类

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");
}

main.cpp

#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
    }
}

1 个答案:

答案 0 :(得分: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();