gpt4 book ai didi

c++ - 多重继承指针和转换

转载 作者:太空宇宙 更新时间:2023-11-04 14:08:17 29 4
gpt4 key购买 nike

给定以下代码:

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* ..?

谢谢

最佳答案

why does it cast v3d to char* first..?

sizeof 产生一个以 bytes 为单位的测量值,而 sizeof(char)1 字节,所以指针(some_char_pointer) + sizeof(Point2d) 执行的数学运算将是正确的。

(相关指针数学复习:)

为便于说明,假设 sizeof(Point2d)16。这个表情...

&v3d + sizeof(Point2d)

...不会&v3d 之后指向 16 字节。它会在 &v3d 之后指向 16 个 Vertex2d。或 16 * sizeof(Vertex2d) 字节。

关于c++ - 多重继承指针和转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16002173/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com