0

ジオメトリ ライブラリを構築していますが、設計上の問題があります。

私はこの(簡略化された)デザインを持っています:

私の基本クラスは 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);
}

それが良い考えではない場合 (そして私はそうではないと思います)、このようなことを行うための良い設計は何でしょうか?

前もって感謝します

(質問のタイトルが悪くてすみません、良いものが見つかりませんでした)

4

1 に答える 1

2

Polylineオブジェクトを作成して返すだけです。

Geometry* intersection(Geometry* other)
{
     Geometry* inter = 0; // Work out what it should be before creating it.

     // Work out what sort of thing it is ...

     if ( someCondition ) // which means it's a Polyline
         inter = new Polyline;

     return inter;
} 

関数は、異なるタイプの Geometry 派生物を作成するため、基本的にファクトリです。a へのポインタが返されますが、必要に応じてa に戻すGeometryこともできます。dynamic_castPolyline

于 2012-04-24T13:22:19.010 に答える