如何返回正确类型的对象

how to return the good type of object

本文关键字:类型 对象 何返回 返回      更新时间:2023-10-16

我正在构建一个几何库,我有一些设计问题。

我有这个(简化的)设计:

我的基类是几何。它实现了计算两个几何图形相交的方法

class Geometry
{
    Geometry* intersection(Geometry* other)
    {
        //...compute intersection...
        //another lib does some work here
        Geometry* inter = compute_intersection()
        return inter;
    }
};

我也有一些从几何派生的类。

假设我有:

class Point : public Geometry
{
};

class Polyline : public Geometry
{
};

我的方法交集返回几何图形,因为我不知道交集的结果是否是点或折线。当我想使用生成的几何图形时,我的问题就来了。

假设在我的主要某个地方,我做

Geometry* geom = somePolyline->intersection(someOtherPolyline);

我知道几何实际上是一条折线。当我尝试做

Polyline* line = dynamic_cast<Poyline*>(geom)

它返回一个 NULL 指针,这是正常的,因为 geom 的实际类型不是折线,而是几何体。我可以尝试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);
}

如果这不是一个好主意(我认为不是),那么做这样的事情会是一个好的设计吗?

提前致谢

(对不起,问题标题很差,我找不到好东西)

只需创建一个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_castPolyline