C++ 重新解释_cast?

标签 c++ reinterpret-cast

我想将 PointsList 类的一个对象转换为另一个对象 Points3DList(反之亦然),其中:

template <class T>
class PointsList
{
    protected:
            std::vector <Point <T> *> points;  //Only illustration, not possible with templaes
};

 template <class T>
class Points3DList
{
    protected:
            std::vector <Point3D<T> *> points;  //Only illustration, not possible with templaes
};

Point 和 Point3D 之间没有任何关系(继承或组合)...

template <class T>
class Point
{
    protected:

            T x;
            T y;

    public:
            Point( const T &x_, const T &y_ ) : x ( x_ ), y ( y_ ) {}
            inline T getX() const {return x;}
            inline T getY() const {return y;}
            inline void setX ( const T &x_ ) {x = x_;}
            inline void setY ( const T &y_ ) {y = y_;}
            ....
};

template <class T>
class Point3D
{
    protected:

            T x;
            T y;
            T z;
};

您如何看待转化

Points3DList <T> *pl3D = new Points3DList <T> ();
...
PointsList <T> *pl = reinterpret_cast < PointList <T> * > ( pl3D );

其中 pl3D 表示指向 Points3DList 对象的指针。在这种情况下可以使用 reinterpret_cast 还是创建一个转换函数更好?这种情况下的数据模型不能改变...

最佳答案

此处的行为将完全未定义。不要这样做!

关于C++ 重新解释_cast?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4707622/

相关文章:

c++ - 在不同限定的结构成员上使用 reinterpret_cast 是否安全?

c++ - reinterpret_cast std::function* 和 void*

c++ - g++-7.0/访问硬件中 constexpr 函数的不同行为

c++ - 避免硬编码枚举类型

c++ - reinterpret_cast 时值发生变化

重新解释模板参数常量的 C++ 编译器行为

c++ - 字符 *数据 = "abc";免费((无效*)数据);为什么要进行 void* 转换?有必要吗?

c++ - 'INT'- 'INT'在C++中表示什么?

c++ - 为什么 printf 将 8 位字符填充为 32 位字符?

c++ - 如何使用 Qt Creator 将视频文件上传到远程 MySQL 服务器