【发布时间】:2011-06-10 02:34:40
【问题描述】:
我想将 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 还是创建转换函数更好?这种情况下的数据模型是不能改变的……
【问题讨论】:
-
这是个糟糕的主意,不要这样做。但是,如果没有
Point和Point3D的定义,很难证明你应该做什么。另外,为什么在向量中存储指向值的指针而不是值本身? -
关于
Point和Point3D类的信息还不够。如果我想转换它们,我需要能够设置它们包含的值。您所展示的只是四个只有受保护成员的类(我如何直接使用它们?)。 -
我假设
Point真的是Point2DCartesian。顺便说一句,您在类定义中定义的成员隐式为inline,您对那里的关键字的使用是多余的。 -
@GMan。这是一个错误,我纠正了它......
-
这仍然是一个错误,因为你有
Point和一个假定的构造函数Point2D;其中之一是不正确的。无论如何,我能再问一次你为什么这么多使用指针吗?
标签: c++ reinterpret-cast