多个继承指针和强制转换
Multiple inheritance pointers & cast
给定以下代码:
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)
字节
相关文章:
- 转换指针引用的字符串
- 无法向上转换指针到指针参数
- 混合转换指针和引用
- 堆栈对象的强制转换指针
- 基类到派生模板类的强制转换指针,而不知道类型
- 删除类型转换指针的最佳方法
- 管理到本机值类转换:强制转换指针是否安全?
- 转换指针类型
- 为什么函数不能正确强制转换指针(从基类到派生类)
- 当我们递增下面的类型转换指针时会发生什么?
- 类型强制转换指针构造函数调用
- 如何转换(指针向量)-->(指向指针数组的指针)
- 如何从类功能转换指针
- 在C++对象中:我应该使用父类强制转换指针,还是应该使用实际类本身进行强制转换
- Delphi中的类型转换指针添加
- C++分段错误(核心转储)错误 - 强制转换指针/将函数值返回到线程
- 以C++和运算符优先级键入指向数组成员的强制转换指针
- C++动态强制转换指针的内存清理
- 转换指针和引用的好处
- 在c++中转换指针