我有一个类:C++多重继承铸造
class Base;
另外我有一个接口
class Interface;
接下来,我创建一个类
class Derived : public Base, public Interface;
如果我有Base *object = new Derived;
我该如何投object
至Interface
? (当然,如果我知道的比对象实际上是一个派生类)
编辑:
我试过的dynamic_cast和的static_cast(不编译)。 所以让我来解释一下这个问题有点多:
我:
class Object {...}
class ITouchResponder
{
public:
virtual bool onTouchBegan(XTouch *touch) = 0;
virtual void onTouchMoved(XTouch *touch) = 0;
virtual void onTouchEnded(XTouch *touch) = 0;
};
class Ball : public Object, public ITouchResponder {...};
class TentacleSensor : public Object, public ITouchResponder {...}
对象有bool touchable_
财产。如果这是真的,则对象正在实现ITouchResponder接口。
当我使用它:
bool Level::onTouchBegan(XTouch *touch)
{
...
ITouchResponder *responder = callback.nearestTouchable();
if (responder)
{
if (responder->onTouchBegan(touch))
{
if (responder != ball_)
{
touch->setUserData(responder);
}
}
}
return true;
}
ITouchResponder *QueryCallback::nearestTouchable() const
{
for (list<Object*>::const_iterator it = objects_.begin(); it != objects_.end(); ++it)
{
if ((*it)->isTouchable()) return (*it)->asTouchResponder();
}
return 0;
}
asTouchResponder
是Object
方法:
ITouchResponder * Object::asTouchResponder()
{
assert(touchable_);
ITouchResponder *res = dynamic_cast<ITouchResponder*>(this);
assert(res);
return res;
}
我在Xcode坏误差过大。
但是,如果我让Object : public ITouchResponder
一切工作正常。我究竟做错了什么 ?
全部对象类:
class Object// : public ITouchResponder
{
public:
struct Def
{
Def()
{
level = 0;
world = 0;
touchable = false;
acceptsContacts = false;
body = 0;
node = 0;
}
Level *level;
b2World *world;
bool touchable;
bool acceptsContacts;
b2Body *body;
XNode *node;
};
Object(const Def &def);
virtual ~Object();
virtual void update(float dt);
bool isTouchable() const {return touchable_;}
void addDependantObject(Object *object);
void removeDependantObject(Object *object);
virtual void objectWillBeRemoved(Object *object) {} //this function is automatically called to every dependant object when object is removed
virtual XVec2 position() const;
virtual float rotation() const;
bool acceptsContacts() const {return acceptsContacts_;}
b2Body *body() const {return body_;}
Level *level() const {return level_;}
b2World *world() const {return world_;}
ITouchResponder *asTouchResponder();
/*
virtual bool onTouchBegan(XTouch *touch) {
return false;
}
virtual void onTouchMoved(XTouch *touch)
{
}
virtual void onTouchEnded(XTouch *touch)
{
}*/
protected:
Level *level_;
b2World *world_;
bool touchable_;
bool acceptsContacts_;
XNode *node_;
b2Body *body_;
list<Object*> dependantObjects_;
};
(派生*)对象 – vivek
@vivek不要在C++代码中使用c转换。为什么引入新的语法是有原因的。 – RedX
理想情况下,您可以使用纯虚拟公共接口,而无需通过调用派生类中重写的接口指针上的方法进行投射,以执行适当的操作。 – AJG85