【发布时间】:2011-10-14 04:09:46
【问题描述】:
假设我有两个不同的类,它们都以相同的内部方式表示二维坐标数据,如下所示:
class LibA_Vertex{
public:
// ... constructors and various methods, operator overloads
float x, y
};
class LibB_Vertex{
public:
// ... same usage and internal data as LibA, but with different methods
float x, y
};
void foobar(){
LibA_Vertex * verticesA = new LibA_Vertex[1000];
verticesA[50].y = 9;
LibB_Vertex * verticesB = reinterpret_cast<LibB_Vertex*>( vertexA );
print(verticesB[50].y); // should output a "9"
};
鉴于这两个类是相同的以及上面的函数,我能否可靠地指望这种指针转换在每种情况下都能按预期工作?
(背景是,我需要一种简单的方法在两个具有相同 Vertex 类的独立库之间交换顶点数组,并且我希望避免不必要地复制数组)。
【问题讨论】: