我有基類形狀並從它繼承像圓,矩形,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」 –