【发布时间】:2017-01-14 11:55:56
【问题描述】:
我有基类 Shape 和一些继承自它的子类,如 Circle、Rectangle、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++ 中的多方法”
标签: c++ oop derived-class visitor-pattern