1.1. 虚成员函数
1.1.1. 单一继承下的虚成员函数
0001 class Point
0002 {
0003 public :
0004 virtual ~Point();
0005 virtual Point &mult(float) = 0;
0006 float X() const { return _x };
0007 virtual float Y() const { return 0 };
0008 virtual float Z() const { return 0 };
0009 protected :
0010 Point(float x = 0.00)
0011 float _x;
0012 };
0013 class Point2d : public Point
0014 {
0015 public :
0016 Point2d (float x = 0.00, float y = 0.00) : Point(x), y(_y) {} ;
0017 virtual ~Point2d();
0018 //改写基类的虚函数
0019 Point2d &mult(float);
0020 float Y() const { return _y };
0021 protected :
0022 float _y;
0023 };
0024 class Point3d : public Point2d
0025 {
0026 public :
0027 Point3d (float x=0.00, y=0.00, z=0.00) : Point2d(x, y), z(_z) {};
0028 virtual ~Point3d();
0029 //改写基类的虚函数
0030 Point3d &mult(float);
0031 float Z() const { return _z };
0032 protected :
0033 float _z;
0034 };
其对象模型如下:
Point object Point Virtual Function Talbe
_x
_vptr_Point
#0
type_info for Point
#1
Point::~Point()
#2
pure vitual called(占位)
#3
Point::y()
#4
Point::z()
Point2d object Point2d Virtual Function Talbe
Point subobject
_x
_vptr_Point
_y
#0
type_info for Point2d
#1
Point2d::~Point2d()
#2
Point2d::mult()
#3
Point2d::y()
#4
Point2d::z()
Point3d object Point3d Virtual Function Talbe
Point2d subobject
_x
_vptr_Point
_y
_z
#0
type_info for Point3d
#1
Point3d::~Point3d()
#2
Point3d::mult()
#3
Point2d::y()//继承
#4
Point3d::z()
Point *ptr;
……
ptr->z();
将被转化为(*ptr->vptr[4])(ptr);