#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;
}
多态中虚构造解析
最新推荐文章于 2025-11-24 22:03:28 发布
本文介绍了一个使用C++编写的计算机系统模型,通过抽象类CPU、VideoCard和Memory,以及它们的具体实现Inter和AMD,展示了如何构造并操作一个包含不同厂商部件的计算机。通过Computer类实例,实现了组件间的交互和功能调用。
252

被折叠的 条评论
为什么被折叠?



