0

我想将 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 还是创建转换函数更好?在这种情况下,数据模型无法更改...

4

3 回答 3

6

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

于 2011-01-16T19:48:28.480 回答
1

您必须编写自己的强制转换函数(构造函数或友元函数)。

就像是:

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

并使用:

PointsList <T> *pl = new PointList( pl3D );
于 2011-01-16T20:06:07.650 回答
0
PointsList <T> *pl = reinterpret_cast < PointList <T> * > ( pl3D );

这没有意义。大错特错。你只会从这样的演员中得到垃圾!

你甚至期望reinterpret_cast如何解释Point并使Point3D选角成功?

于 2011-01-16T19:49:49.750 回答