#include <iostream>
using namespace std;
//1.抽象出每个零件的类
class CPU//CPU
{
//纯虚函数
public:
virtual void calculate() = 0;//抽象计算函数
};
class VideoCard//显卡
{
public:
virtual void display() = 0;//抽象显示函数
};
class Memory//内存条
{
public:
virtual void storage() = 0;//抽象存储函数
};
//2.电脑类
class Computer
{
public:
Computer(CPU* cpu,VideoCard* vc,Memory* mem)//构造函数中传入三个零件指针
{
m_cpu = cpu;
m_vc = vc;
m_mem = mem;
}
//3.提供工作函数,调用每个零件工作的接口
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;
};
//4.具体零件厂商
class InterCPU:public CPU
{
public:
virtual void calculate()
{
cout << "Inter的CPU正在工作" << endl;
}
};
class InterVideoCard :public VideoCard
{
public:
virtual void display()
{
cout << "Inter的display正在工作" << endl;
}
};
class InterMemory :public Memory
{
public:
virtual void storage()
{
cout << "Inter的storage正在工作" << endl;
}
};
class LenvoCPU :public CPU
{
public:
virtual void calculate()
{
cout << "Lenvo的CPU正在工作" << endl;
}
};
class LenvoVideoCard :public VideoCard
{
public:
virtual void display()
{
cout << "Lenvo的display正在工作" << endl;
}
};
class LenvoMemory :public Memory
{
public:
virtual void storage()
{
cout << "Lenvo的storage正在工作" << endl;
}
};
//5.测试函数,组装三台不同的电脑
void test01()
{
//第一台电脑
CPU* interCpu = new InterCPU;//利用Computer中的析构函数释放
VideoCard* interCard = new InterVideoCard;
Memory* interMem = new InterMemory;
Computer* computer1=new Computer(interCpu,interCard,interMem);
cout << "第一台电脑:" << endl;
computer1->work();
delete computer1;
Computer* computer2 = new Computer(new LenvoCPU, new LenvoVideoCard,new LenvoMemory);
cout << "==========" << endl;
cout << "第二台电脑:"<< endl;
computer2->work();
delete computer2;
cout << "==========" << endl;
cout << "第三台电脑:" << endl;
Computer* computer3 = new Computer(new InterCPU, new LenvoVideoCard, new LenvoMemory);
computer3->work();
delete computer3;
}
int main()
{
test01();
return 0;
}
多态案例-电脑组装
最新推荐文章于 2024-06-12 20:44:27 发布