Is it possible to have polymorphic member overloading in C++?

别来无恙 提交于 2019-12-25 04:38:22

问题


I have been working on a Roguelike, and run into a problem with it. My problem is that I would like to use "polymorphic overloading" or sorts, but I'm guessing C++ doesn't support.

My class diagram is like this:

xMapObject <- xEntity <- xVehicle

An the problem is, it is possible to have this:

class xMapObject
{
  public:
    virtual void Bump(xMapObject *MapObject);
    virtual void Bump(xEntity *Entity);
    virtual void Bump(xVehicle *Vehicle);

    virtual void BumpedBy(xMapObject *MapObject);
    virtual void BumpedBy(xEntity *Entity);
    virtual void BumpedBy(xVehicle *Vehicle);
};

This would be a very nice, as it would great simplify the code that determines who bumps into what, but since this doesn't work, is there another object oriented approach similar to this? Or is the best option casting objects to determine what they are?

Thanks for any help!


回答1:


Sure it works. I think though that you expect it to be able to tell the difference when you pass it an xMapObject* and that simply won't happen.

You need a double dispatch mechanism. Perhaps visitor but I'm doubting it. See Modern C++ Design or wiki for multimethods.




回答2:


It's possible, but this design seems awkward to me.

namespace {

class xEntity;
class xVehicle;

class xMapObject {
  public:
    virtual void Bump(xMapObject *MapObject);
    virtual void Bump(xEntity *Entity);
    virtual void Bump(xVehicle *Vehicle);

    virtual void BumpedBy(xMapObject *MapObject);
    virtual void BumpedBy(xEntity *Entity);
    virtual void BumpedBy(xVehicle *Vehicle);
};

class xEntity : public xMapObject {};

class xVehicle : public xMapObject {};

}

I think I would do something like this instead:

namespace {

class xMapObject {
public:
    virtual void Bump(xMapObject *MapObject);
    virtual void BumpedBy(xMapObject *MapObject);
};

class xEntity : public xMapObject {
public:
    void Bump(xMapObject *MapObject);
    void BumpedBy(xMapObject *MapObject);
};

class xVehicle : public xMapObject {
public:
    void Bump(xMapObject *MapObject);
    void BumpedBy(xMapObject *MapObject);
};

}


来源:https://stackoverflow.com/questions/4665602/is-it-possible-to-have-polymorphic-member-overloading-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!