virtual function
一般实现模型:每个class有一个virtual table, 内含该class之中有作用的virutal function
的地址,然后每个object
有一个vptr
,指向virtual table
所在;考虑如下代码:
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;
};
class Point2d : public Point{
public:
Point2d(float x = 0.0, float y = 0.0) :
Point(x), _y(y){}
~Point2d();
Point2d& mult(float);
float y() const {return _y;}
protected:
float _y;
};
class Point3d : public Point2d{
public:
Point3d(float x = 0.0, float y = 0.0, float z = 0.0) :
Point2d(x, y), _z(z){}
~Point3d();
Point& mult(float);
float z() const {return _z;}
protected:
float _z;
};
下图为Point
的内存布局和其virtual table
多重继承下的virutal functions
class Base1 {
public:
Base1();
virtual ~Base1();
virtual void speakClearly();
virtual Base1 *clone() const;
protected:
float data_Base1;
};
class Base2 {
public:
Base2();
virtual ~Base2();
virtual void mumble();
virtual Base2 *clone() const;
protected:
float data_Base2;
};
class Derived : public Base1, public Base2 {
public:
Derived();
virtual Derived *clone() const;
protected:
float data_Derived;
};