Is it possible to have polymorphic member overload

2019-09-07 09:34发布

问题:

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

}