zoukankan      html  css  js  c++  java
  • 虚继承

    /*虚继承*/

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

  • 相关阅读:
    《数据结构与算法之美》03——数组
    设计模式系列三-代理模式
    Docker系列2-image详解
    docker系列2-centos7下安装docker
    docker系列1-简介
    idea设置JDK无效
    java引用传递还是值传递问题解析
    MySQL优化系列4-全文索引
    MySQL优化系列3-存储引擎
    Redis深入解析系列:分布式锁详解
  • 原文地址:https://www.cnblogs.com/w413133157/p/1660170.html
Copyright © 2011-2022 走看看