4.2 Virtual Member Functions

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;
};

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值