VTABLE(虚表)的结构

来源:互联网 发布:eset知乎 编辑:程序博客网 时间:2024/05/18 20:47
VTABLE(虚表)的结构
--uper

以下是vtable和class的对应关系
 class Point
class Point{
public:
    
virtual ~Point();
    
virtual Point& mult(float= 0;
    
float x() const{return _x;}
    
virtual float y() const{return 0;}
    
virtual float z() const{return 0;}

protected:
    Point(
float x=0.0){};
    
float _x;
}
vtable.point
class Point2d 继承了class Point
class Point2d : public Point{
public:
    Point2d(
float x=0.0float y=0.0) : Point(x), _y(y){};
    
virtual ~Point2d();
    
virtual Point2d& mult(float);    
    
virtual float y() const{return _y;}
protected:
    
float _y;
}
vtable.Point2d
class Point3d 继承了Point2d
class Point3d : public Point2d{
public:
    Point3d(
float x=0.0float y=0.0float z=0.0) : Point2d(x, y), _z(z){};
    
virtual ~Point3d();
    
virtual Point3d& mult(float);    
    
virtual float z() const{return _z;}
protected:
    
float _z;
}

vtable.Point3d
对于ptr->y(), 编译器并不知道最终会调用哪个类的有y(), 编译器仅仅将其转换成:
(*ptr->vptr[3])(ptr);
vptr: 编译器产生的指向vtable的指针
3:y()在vtable中的index位置

在运行过程中,ptr会被赋予不同的对象,只有到那时才能知道某个对象通过vptr调用了自己vtable里的y().
原创粉丝点击