如何返回好的对象类型

时间:2012-04-24 13:14:54

标签: c++ casting

我正在构建几何库,但我遇到了一些设计问题。

我有这个(简化)设计:

我的基类是Geometry。它实现了一种计算两个几何的交集的方法

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
{
};

我的方法交集返回几何,因为我不知道交叉的结果 是点或折线。当我想使用生成的几何体时,我的问题出现了。

让我说在我的主要地方,我做

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);
}

如果这不是一个好主意(而且我认为不是这样),做这样的事情会有什么好处?

提前致谢

(抱歉问题很糟糕,我找不到好的东西)

1 个答案:

答案 0 :(得分: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的指针,但如果需要,您可以dynamic_cast将其指向Polyline

相关问题