我想将 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/