0

C++ 是我广泛使用的第一种使用面向对象的语言,所以我对这个想法还是有点陌生​​。我正在尝试将我正在开发的游戏库从 Go(它使用接口而不是真正的 OOP 系统)移植到 C++。

我有一个使用四种类型的碰撞系统:点、边界、线和多边形。我想做的是让所有这些都可以抽象成一个“碰撞器”类,并具有一个能够获取两个碰撞器对象并测试碰撞的函数。它看起来像这样:

bool Collides(Collider obj1, Collider obj2);

最初我想我可以为每种碰撞类型设置方法来测试给定另一种类型的碰撞(即方法 OnPoint、OnBounding、OnLine 和 OnPolygon),然后让“Collider”成为需要所有这些方法的虚拟类,但是然后我意识到这在 C++ 中是不可能的,因为它会使类相互依赖以进行编译(对吗?)。

我有点不知所措,我还能做什么。我的设计理念是白日梦吗?

4

1 回答 1

1

你想要的是一个函数,它不仅在第一个参数上分派,而且在第二个参数上分派,即双重分派。这在 C++ 中不直接支持,但可以模拟。

class Point;
class Line;

class Collider {
public:
  virtual bool Collides(Collider const& x) const = 0;

protected:
  virtual bool Collides(Point const& p) const = 0;
  virtual bool Collides(Line const& l) const = 0;

  friend class Point;
  friend class Line;
};

class Point: public Collider {
public:
  virtual bool Collides(Collider const& x) const {
    // here, the type of this is now Point
    // now, find out what x is and call the overload on this type
    return x.Collides(*this);
  }

protected:
  virtual bool Collides(Point const& p) const {
    return false;
    // we now know that we are a point and checking vs. another point
  }

  virtual bool Collides(Line const& l) const {
    return false;
    // we now know that we are a point and checking vs. a line
  }
};

class Line: public Collider {
public:
  virtual bool Collides(Collider const& x) const {
    // here, the type of this is now Line 
    return x.Collides(*this);
  }

protected:
  virtual bool Collides(Point const& p) const {
    return false;
    // we now know that we are a line and checking vs. a point
  }

  virtual bool Collides(Line const& l) const {
    return false;
    // we now know that we are a line and checking vs. another line
  }
};

现在,检查两个对象将执行两个运行时调度:

Collider* p = new Point();
Collider* l = new Line();

p->Collides(*l);
// first dynamically dispatches on p to call Point::Collides
// in Collides, this (which is p) now has the static Point. 
// now do the second dispatch on l and use *this as the parametet
// to find the overload.

这例如用在访问者设计模式中。如果您的对象集是固定的,但您希望对它们执行的操作会更改或扩展,那么 Visitor 是一个不错的选择。

于 2014-04-06T21:53:24.347 回答