如何返回正确类型的对象
how to return the good type of object
我正在构建一个几何库,我有一些设计问题。
我有这个(简化的)设计:
我的基类是几何。它实现了计算两个几何图形相交的方法
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_cast
到Polyline
。
相关文章:
- std::unordered_map 类型对象声明期间出现"field has incomplete type"错误
- C++ 多态模板类,模板类型对象的实例化
- 如何分配适合容纳 T 类型对象的缓冲区(可能过度对齐、可能有运算符 new 等)
- 如何构造一个 std::variant 类型对象,其自身 Templated 和构造函数转发参数
- C++:初始化指向具有不同类型对象的指针数组
- 在类 C++ 中构造的模板类型对象
- 如何将颁发者名称设置为x509_req类型对象
- 将任何数据类型/对象作为参数传递以确定其大小
- 将引用类型对象的数组从C#封送到C++
- <T> 从类型对象创建类型<T1>对象的构造函数
- C++是否有现有的方法来检查对象是否是派生类型对象
- C 模板:创建与现有对象相同的类型对象
- 链接列表中的虚函数 - 多种返回类型(对象)
- 没有适当操作员()的类型对象的呼叫
- 制作垫子类型对象的数组.输出窗口显示同一帧
- 抽象类型对象的分配
- 在std::list中就地创建自定义类型对象
- 接受泛型列表类型对象的参数
- C++-将模板类型对象强制转换为特定的数据类型
- 试图在C++中打印存储在类型对象数组中的信息