派生类的 C++ reinterpret_cast

标签 c++ derived-class reinterpret-cast

父类:

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/

相关文章:

c++ - 重新解释_cast<const char*> 任何以 char[size] 成员开头的结构是否安全?

c++ - 您如何在大型 C++ 项目中实现单元测试?

c++ - 派生类中的运算符<< C++

c++ - 上下文共享在带有 glfw 和 glew 的 opengl 中不起作用,第二个窗口就像上下文根本不共享

c++ - C++中的派生类

c++ - 不从派生类调用基类构造函数

c++ - 从 char 数组末尾读取 4 个字节

c++ - 为什么 reinterpret_cast 在某些情况下有效而在其他情况下无效?

c++ - 为 C++ Windows 服务动态创建安装程序

c++ - 重载运算符 : Matrix Addition