- 多重继承
namespace ObjectMultiDerived {
class Point2d {
public:
// has virtual functions
virtual void print() {};
private:
float _x;
float _y;
};
class Point3d : public Point2d {
public:
// ...
private:
float _z;
};
class Vertex {
public:
// has virtual functions
virtual void print() {};
private:
Vertex* next;
};
class Vertex3d : public Point3d, public Vertex {
public:
// ...
private:
float mumble;
};
void test()
{
cout << "Point2d类、Point3d类、Vertex、Vertex3d类的大小:" << sizeof(Point2d) << " "
<< sizeof(Point3d) << " " << sizeof(Vertex) << " " << sizeof(Vertex3d) << endl;
}
}
ObjectConDerived::test();//Point2d类、Point3d类、Vertex、Vertex3d类的大小:12 16 8 28
Vertex3d v3d;
Point2d* p2d;
Point3d* p3d;
//直接拷贝地址
p2d = &v3d;
p3d = &v3d;
//需要调整this指针的位置
Vertex* pv;
Vertex3d *pv3d;
pv = pv3d; //编译器伪码为:pv = (Vertex*) ( ((char*)pv3d) + sizeof(Point3d));
pv = &v3d; // 编译器伪码为:pv = (Vertex*) ( ((char*)&v3d) + sizeof(Point3d));
【引用】
[1]: <<深度探索C++ 对象模型 Inside The C++ Object Model >> Stanley B.Lippman 候捷 译
[2]: 代码地址 https://github.com/thefistlei/cplusStudy.git