ジオメトリ ライブラリを構築していますが、設計上の問題があります。
私はこの(簡略化された)デザインを持っています:
私の基本クラスは Geometry です。2 つのジオメトリの交差を計算するメソッドを実装します。
class Geometry
{
Geometry* intersection(Geometry* other)
{
//...compute intersection...
//another lib does some work here
Geometry* inter = compute_intersection()
return inter;
}
};
Geometry から派生したクラスもいくつかあります。
私が持っているとしましょう:
class Point : public Geometry
{
};
と
class Polyline : public Geometry
{
};
交差の結果が Point なのか Polyline なのかがわからないため、交差メソッドはジオメトリを返します。私の問題は、結果のジオメトリを使用したいときに発生します。
私のメインのどこかで言ってみましょう、私はそうします
Geometry* geom = somePolyline->intersection(someOtherPolyline);
geom が実際にはポリラインであることは知っています。やろうとすると
Polyline* line = dynamic_cast<Poyline*>(geom)
NULL ポインターを返します。geom の実際の型は Polyline ではなく、Geometry であるため、これは正常です。reinterpret_cast を試すことはできますが、ポリモーフィックな動作が失われます。
私の質問は次のとおりです。交差メソッドを次のように変更できますか:
Geometry* intersection(Geometry* other)
{
//...compute intersection...
Geometry* inter = compute_intersection()
// the intersection is computed by another lib and I can check (via a string)
// the real type of the returned geometry.
// cast the result according to its real type
if (inter->realType() == "Polyline")
return dynamic_cast<Polyline*>(inter);
}
それが良い考えではない場合 (そして私はそうではないと思います)、このようなことを行うための良い設計は何でしょうか?
前もって感謝します
(質問のタイトルが悪くてすみません、良いものが見つかりませんでした)