/*虚继承*/

#include "stdafx.h"
#include <iostream.h>

class furniture
{
public:
    furniture( int nWeight )
    {
        m_nWeight = nWeight;
        cout << "
家具的构造" << endl;
    }
    int m_nWeight;
};

//
虚继承
//
使派生类对象只有一份基类(furniture)的拷贝
//
在菱形继承下,在上面的两个继承关系中,加上虚继承

class Safa : virtual public furniture
{
public:
    Safa( int nWeight ):furniture(nWeight)
    {
        cout << "
沙发的构造" << endl;
    }
    void sit()
    {
       
    }
};

class Bed : virtual public furniture
{
public:
    Bed( int nWeight ):furniture(nWeight)
    {
        cout << "
床的构造" << endl;
    }
    void sleep()
    {
       
    }
};

//
构造顺序,先是虚基类
//
在是非虚基类,按声明的顺序构造
class SafaBed :public Bed,public Safa
{
public:
    SafaBed( int nWeight ): Safa(nWeight),Bed(nWeight),furniture(nWeight)
    {
        Bed::m_nWeight = nWeight;
        cout << "
沙发床的构造" << endl;
    }
};

int main(int argc, char* argv[])
{
    SafaBed theSafaBed(100);   
    furniture* pFurniture = (Bed*)&theSafaBed;   
    theSafaBed.sit();   
    theSafaBed.sleep();   
    cout << sizeof(theSafaBed) << endl;
   
    return 0;
}

posted on 2010-01-30 19:06  o无尘o  阅读(212)  评论(0编辑  收藏  举报