我正在构建一个几何库,但遇到了一些设计问题。
我有这个(简化的)设计:
我的基类是几何。它实现了一种计算两个几何图形的交集的方法
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);
}
如果这不是一个好主意(我认为它不是),做这样的事情会是一个好的设计吗?
提前致谢
(抱歉问题标题不好,我找不到好东西)
最佳答案
只需创建一个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
。
关于c++ - 如何返回好的类型的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10298594/