我有基类形状并从它继承像圆,矩形,AlignedRectangle,ConvexPolygon,ConcavePolygon等一些亚类我想每个这样的类的具有方法 bool intersect(Shape &other);
如果两个形状相交,其检查。我想为不同的类对使用这种方法的不同实现,因为某些交点可以比蛮力方法快得多。 我想要这样的方法,所以我可以交叉两个Shape *指针而不关心实际内部的类型。动态型匹配
这是我目前的做法。
class Circle;
class Rect;
class Shape {
public:
Shape() {}
virtual bool intersect(Shape &a) = 0;
virtual bool intersect_circle(Circle &a) = 0;
virtual bool intersect_rect(Rect &a) = 0;
};
class Circle : public Shape {
public:
Circle() {}
virtual bool intersect(Shape &a);
virtual bool intersect_circle(Circle &a);
virtual bool intersect_rect(Rect &a);
};
class Rect : public Shape {
public:
Rect() {}
virtual bool intersect(Shape &a);
virtual bool intersect_circle(Circle &a);
virtual bool intersect_rect(Rect &a);
};
bool Circle::intersect(Shape &a) {
a.intersect_circle(*this);
}
bool Circle::intersect_circle(Circle &a) {
cout << "Circle::intersect_circle" << endl;
}
bool Circle::intersect_rect(Rect &a) {
cout << "Circle::intersect_rect" << endl;
}
bool Rect::intersect(Shape &a) {
a.intersect_rect(*this);
}
bool Rect::intersect_circle(Circle &a) {
cout << "Rect::intersect_circle" << endl;
}
bool Rect::intersect_rect(Rect &a) {
cout << "Rect::intersect_rect" << endl;
}
有一些其他的,“好”的方式来做到这一点? 对于两个形状的交集可能没有问题,但是如果我想拥有两个或多个可以有任何类型的参数的方法呢?这是3类案例的延伸:
void Circle::some_stuff(Shape &a, Shape &b) {
a.some_stuff_circle(*this, b);
}
void OtherClass::some_stuff_circle(Circle &a, Shape &b) {
b.some_stuff_circle_other_class(a, *this);
}
void AnotherClass::some_stuff_circle_other_class(Circle &a, OtherClass &b) {
//do things here
}
这会有很多冗余代码。我可能会错过一些基本的东西。
您已重新创建访问者模式。顺便说一句,多重参数动态调度是Bjarne写的,因此将来可能会出现在标准C++中。您可能想搜索“C++中的multimethods” –