4.7.6 多态案例三-电脑组装

4.7.6 多态案例三-电脑组装_第1张图片

#include
using namespace std;

//抽象不同零件类

//抽象CPu类
class Cpu 
{
    //抽象计算函数
    virtual void Calculator()=0;
};
//抽象显卡类
class VideaCard
{
    //抽象显示函数
    virtual void display()=0;
};
//抽象内存条类
class Memory
{
    //抽象存储函数
    virtual void storage()=0;
};

//抽象电脑类
class Computer
{
    //构造函数中传入三个零件指针
public:
    Computer(Cpu *cpu,VideoCard *vc,Memory *mem)
    {
        m_cpu=cpu;
        m_vc=vc;
        m_mem=mem;    
}
    //提供析构函数 释放3个电脑零件
    ~Computer()
    {
        if(m_cpu!=NULL)
        {
            delete m_cpu;
            m_cpu=NULL;
        }
        if(m_vc!=NULL)
        {
            delete m_vc;
            m_vc=NULL;
        }
        if(m_mem!=NULL)
        {
            delete m_mem;
            m_mem=NULL;
        }
    }
    //提供工作函数 调用每个零件工作的借口
    void work()
    {
        //让零件工作起立,调用借口
        m_cpu->calcalate();
        m_vc->display();
        m_mem->storage();
    }

private:
    Cpu *m_cpu;    
    VideoCard *m_vc;
    Memory *m_mem;
}
//具体厂商
//Intel 厂商
class IntelCpu: public Cpu
{
public:
    virtual void calculate()
    {
        cout<<"Intel的CPU开始计算了"
    }
};
class IntelVideoCard: public VideoCard
{
public:
    virtual void display()
    {
        cout<<"Intel的显卡开始显示了"
    }
};
class IntelMemory: public Memory
{
public:
    virtual void storage()
    {
        cout<<"Intel的内存条开始存储了"
    }
};

//Lenovo厂商
class LenovoCpu: public Cpu
{
public:
    virtual void calculate()
    {
        cout<<"Lenovo的CPU开始计算了"
    }
};
class LenovoVideoCard: public VideoCard
{
public:
    virtual void display()
    {
        cout<<"Lenovo的显卡开始显示了"
    }
};
class LenovoMemory: public Memory
{
public:
    virtual void storage()
    {
        cout<<"Lenovo的内存条开始存储了"
    }
};

void test01()
{
    //第一台电脑零件
    Cpu *intelCpu=new IntelCpu;
    VideoCard *intelCard= new IntelVideoCard;
    Memory *intelMem=new IntelMemory;
    
    //创建第一台电脑
    Computer *computer1 =new Computer(intelCpu,intelCard,intelMem);
    computer1->work();
    delete computer1;
       
    //第二台电脑组装
    Computer *computer2 =new Computer(new LenovoCpu,new LenovoCard,new LenovoMem);
    computer2->work();
    delete computer2;
    

}

int main()
{
    test01();
    system("pause");
    return 0;
}









 

你可能感兴趣的:(c++,蓝桥杯,开发语言)