多个继承指针和强制转换

Multiple inheritance pointers & cast

本文关键字:转换 指针 继承      更新时间:2023-10-16

给定以下代码:

namespace Try {
class Point2d {
    float _x, _y;
public:
    Point2d(float x, float y) : _x(x), _y(y) {}
};
class Vertex {
    Vertex* next;
public:
    Vertex(Vertex* n) : next(n) {}
    Vertex() {}
};
class Vertex2d : public Point2d, public Vertex {
    float mumble;
public:
    Vertex2d(float x, float y, float mum) : Point2d(x,y), mumble(mum) {}
};
}
int main (void)
{
using Try::Point2d;
using Try::Vertex;
using Try::Vertex2d;
Vertex2d v3d(2.5,3,4);
Vertex*  pv;
Point2d* pp;
pv = &v3d;      
pv = (Vertex*)(((char*)&v3d) + sizeof(Point2d));
}

谁能解释一下为什么最后两个命令:

pv = &v3d;
pv = (Vertex*)(((char*)&v3d) + sizeof(Point2d));

(我猜这就是编译器将pv = &v3d翻译成…)

是完全相同的?我可以理解(+sizeof(Point2d))的存在,因为Vertex2d首先是Point2d,所以我们必须添加大小才能到达"顶点"部分。但是为什么它先将v3d转换为char* ?

谢谢

为什么它先将v3d转换为char* ?

sizeof产生一个字节的测量sizeof(char)1字节,因此(some_char_pointer) + sizeof(Point2d)执行的指针数学运算是正确的。

(一个相关的指针数学复习:)

为了说明,假设sizeof(Point2d)16。这个表达式…

&v3d + sizeof(Point2d)

…would not point 16 bytes&v3d之后。它将在&v3d之后指向16 Vertex2d s。或者16 * sizeof(Vertex2d)字节