简体   繁体   中英

C++ reinterpret cast?

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...

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

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 );
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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM