父类:
template <class T>
class Point
{
protected
T x;
T y;
};
派生类:
template <class T>
class Point3DTopo: public Point <T>
{
protected:
T z;
Face <T> *face; //Points to any face
};
我想将 PointsList 类的一个对象转换为另一个对象 Points3DTopoList(反之亦然),其中:
template <class T>
class PointsList
{
protected:
std::vector <Point <T> *> points; //Only illustration, not possible with templaes
};
template <class T>
class Points3DTopoList
{
protected:
std::vector <Point3DTopo <T> *> points; //Only illustration, not possible with templaes
};
是否允许这样的转换?
Points3DTopoList <T> *pl = new Points3DTopoList <T> ();
...
PointsList <T> *pl = reinterpret_cast < PointsList <T> * > ( pl3D );
然后反向转换?
PointsTopoList <T> *pl = new PointsTopoList <T> ();
...
Points3DTopoList <T> *pl3D = reinterpret_cast < Points3DTopoList <T> * > ( pl );
每个Point3Topo的Face指针会被初始化为NULL还是未定义?
最佳答案
这样的转换是不允许的。这是一个基本问题:您要么必须通过复制进行转换,要么调整您的类定义,以便您拥有 ListOf<PointT, T>
,即在点类型和点内的类型上进行参数化。
但是,类设计无论如何都是有缺陷的:你不应该派生 Point3D
来自 Point
, 这违反了 Liskov substitution principle (LSP) – 或者更一般地说:3D 点不是 2D 点。事实上恰恰相反:2D 点是 3D 点的特例。
所以如果你想在这里继承,它应该以另一种方式进行(即 2D 继承自 3D)但这很可能也违反 LSP,并且非常尴尬(从那时起您的 2D 点将有一个始终固定的冗余变量)。简单地说,2D点和3D点之间没有合适的继承关系,它们是不同的实体。
关于派生类的 C++ reinterpret_cast,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4721649/