多态中虚构造解析

#include <iostream>
#include <string>
using namespace std;
//电脑:CPU+MEMORY+VIDEOCARD,每个类都由抽象类和具体类构成;
class CPU{
public:
    virtual void cal() = 0;//纯虚函数
};
class InterCPU: public CPU{
    void cal(){
        cout<< "Inter厂商的CPU开始进行计算!" <<endl;
    }
};
class AMDCPU: public CPU{
    void cal(){
        cout<< "AMD厂商的CPU开始进行计算!" <<endl;
    }
};
class VideoCard{
public:
    virtual void display() = 0;
};
class InterVideoCard: public VideoCard{
    void display(){
        cout<< "Inter厂商的VideoCard开始进行显示!" <<endl;
    }
};
class Memory{
public:
    virtual void storge() = 0;
};
class InterMemory: public Memory{
    void storge(){
        cout<< "Inter厂商的Memory开始进行存储!" <<endl;
    }
};
class Computer{
public:
    Computer(CPU* cpu, VideoCard* vc, Memory* mem) //构造函数
    {
        m_cpu = cpu;
        m_vc = vc;
        m_mem = mem;
    }
    void work(){ //调用接口
        m_cpu->cal();
        m_vc->display();
        m_mem->storge();
    }
    ~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;
        }
    }
private:
    CPU* m_cpu;
    VideoCard* m_vc;
    Memory* m_mem;
};
void test(){
    CPU* cpu = new InterCPU;
    CPU* cpu1 = new AMDCPU;
    VideoCard* videoCard = new InterVideoCard;
    Memory* memory = new InterMemory;

    Computer* computer01 = new Computer(cpu, videoCard, memory);
    computer01->work();

    delete computer01;
}

int main()
{
    test();
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值