virtual base classes

来源:互联网 发布:程序员写博客的好处 编辑:程序博客网 时间:2024/05/20 01:45

virtual base classes用来实现菱形继承解决多个重复subobject的问题

//: C09:VirtualBase.cpp// Shows a shared subobject via a virtual base.#include <iostream>using namespace std;class Top{protected:    int x;public:    Top(int n)    {        x = n;    }    virtual ~Top() {}    friend ostream&    operator<<(ostream& os, const Top& t)    {        return os << t.x;    }};class Left : virtual public Top{protected:    int y;public:    Left(int m, int n) : Top(m)    {        y = n;    }};class Right : virtual public Top{protected:    int z;public:    Right(int m, int n) : Top(m)    {        z = n;    }};class Bottom : public Left, public Right{    int w;public:    Bottom(int i, int j, int k, int m)        : Top(i), Left(0, j), Right(0, k)    {        w = m;    }    friend ostream&    operator<<(ostream& os, const Bottom& b)    {        return os << b.x << ',' << b.y << ',' << b.z               << ',' << b.w;    }};int main(){    Bottom b(1, 2, 3, 4);    cout << sizeof b << endl;    cout << b << endl;    cout << static_cast<void*>(&b) << endl;    Top* p = static_cast<Top*>(&b);    cout << *p << endl;    cout << static_cast<void*>(p) << endl;    cout << dynamic_cast<void*>(p) << endl;    return 0;} ///:~

输出结果:

281,2,3,40043FABC10043FAD00043FABC
对象大小与实现有关,28 = 4 * 4 + 2 * 4 + 1 * 4(大概是4个int,2个ptr to virtual base,1 个vptr)

注意Bottom里初始化Top的方式,Left、Right给出的对应参数会被编译器巧妙地忽略


内容源自:《TICPP-2nd-ed-Vol-two》

0 0
原创粉丝点击