C++ reinterpret cast?

僤鯓⒐⒋嵵緔 提交于 2020-01-06 09:56:07

问题


I would like to cast one object of the class PointsList to another object Points3DList (and vice versa) where:

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

and

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

Between Point and Point3D there is no relationship (inheritance nor composition)...

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;
};

What do you think about conversion

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

where pl3D represents pointer to Points3DList object.. Can reinterpret_cast be used in this case or it is better to create a conversion function? Data model in this case can not be changed...


回答1:


The behaviour here will be completely undefined. Don't do it!




回答2:


You must write your own cast function (constructor or friend function).

Something like:

template <class T>
class PointsList
{
    PointsList(Points3DList& p3d) : x(p3d->x), y(p3d->y) {};
... 

And use:

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



回答3:


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

This doesn't make sense. Terribly Wrong. You'll get only garbage out of such cast!

How do you even expect reinterpret_cast to interpret Point and Point3D to make the casting succeed?



来源:https://stackoverflow.com/questions/4707622/c-reinterpret-cast

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!