#include<iostream>
using namespace std;
class CPU{
public:
virtual void calculate() = 0;
};
class VideoCard{
public:
virtual void display() = 0;
};
class Memory{
public:
virtual void storage() = 0;
};
class Computer{
public:
Computer(CPU *cpu, VideoCard *vc, Memory *mem){
m_cpu = cpu;
m_vc = vc;
m_mem = mem;
}//构造
void work(){
//调用结构
m_cpu->calculate();
m_vc->display();
m_mem->storage();
}
~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;
};
//Interl
class InterlCPU : public CPU{
public:
virtual void calculate(){
cout << "Interl的CPU开始计算" << endl;
}
};
class InterlVideoCard : public VideoCard{
public:
virtual void display(){
cout << "Interl的ViderCard开始显示" << endl;
}
};
class InterlMemory : public Memory{
public:
virtual void storage(){
cout << "Interl的Memory开始存储" << endl;
}
};
//Lenovo
class LenovoCPU : public CPU{
public:
virtual void calculate(){
cout << "Lenovo的CPU开始计算" << endl;
}
};
class LenovoVideoCard : public VideoCard{
public:
virtual void display(){
cout << "Lenovo的VideoCard开始显示" << endl;
}
};
class LenovoMemory : public Memory{
public:
virtual void storage(){
cout << "Lenovo的Memory开始存储" << endl;
}
};
void test(){
CPU * interlCpu = new InterlCPU;
VideoCard * interlCard = new InterlVideoCard;
Memory * interlMem = new InterlMemory;
Computer * computer1 = new Computer(interlCpu, interlCard, interlMem);
computer1 -> work();
delete computer1;
cout << "---------------------" << endl;
CPU * interlCpu2 = new InterlCPU;
VideoCard * lenovolCard2 = new LenovoVideoCard;
Memory * interlMem2 = new InterlMemory;
Computer * computer2 = new Computer(interlCpu2, lenovolCard2, interlMem2);
computer2 -> work();
delete computer2;
cout << "---------------------" << endl;
CPU * LenovoCpu3 = new LenovoCPU;
VideoCard * LenovoCard3 = new LenovoVideoCard;
Memory * LenovoMem3 = new LenovoMemory;
Computer * computer3 = new Computer(LenovoCpu3, LenovoCard3, LenovoMem3);
computer2 -> work();
delete computer2;
}
int main(){
test();
return 0;
}
多态案例——电脑
最新推荐文章于 2024-09-17 19:56:07 发布