我有从类Ball
派生的PhysicsObject
类。在以下方法中,我从指针获取Ball
实例并检查其是否为 type 。当我调用该方法时,它不会在类对象中被调用。我在这里做错了什么?void
PhysicsObject
collidingWith
Ball
更新 我在底部添加了一个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.cpp
foo()
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
}
}