电脑组装
#include <iostream>
#include <string>
using namespace std;
class CPU { public: virtual void Calc() = 0; };
class GPU { public: virtual void Display() = 0; };
class RAM { public: virtual void Storge() = 0; };
class Computer {
public:
Computer(CPU* cpu, GPU* gpu, RAM* ram) { //将组成电脑的三个组件传进来
this->m_CPU = cpu; //成员组件将会是传进来的内容
this->m_GPU = gpu;
this->m_RAM = ram;
}
void Work() { //工作函数调用
m_CPU->Calc();
m_GPU->Display();
m_RAM->Storge();
}
~Computer() { //自身的析构释放堆数据
if (m_CPU != NULL) {
delete m_CPU;
m_CPU = NULL;
}else if (m_GPU != NULL) {
delete m_GPU;
m_GPU = NULL;
}
else if(m_RAM != NULL) {
delete m_RAM;
m_RAM = NULL;
}
}
private:
CPU* m_CPU;
GPU* m_GPU;
RAM* m_RAM;
};
class IntelCPU:public CPU { //Intel的CPU必须继承CPU的纯虚函数
public:
void Calc() {
cout << "Intel CPU Processing" << endl;
}
};
class IntelGPU :public GPU {
public:
void Display() {
cout << "Intel GPU Displaying Images" << endl;
}
};
class IntelRAM:public RAM{
public:
void Storge() {
cout << "Intel RAM Storging Data" << endl;
}
};
class DellRAM :public RAM {
public:
void Storage() {
cout << "Dell RAM Storageing Data" << endl;
}
};
class DellGPU :public GPU {
public:
void Display() {
cout << "Dell GPU Displaying Images" << endl;
}
};
class DellCPU :public CPU {
public:
void Calc() {
cout << "Dell CPU Processing" << endl;
}
};
void example(){
CPU* cpu = new IntelCPU;//CPU使用IntelCPU进行创建
GPU* gpu = new DellGPU;//在堆区创建GPU
RAM* ram = new IntelRAM;
Computer *PC1 = new Computer(cpu, gpu, ram);
//在堆区创建电脑,然后在堆区进行组装
PC1->Work();
delete PC1;//释放掉
}
int main() {
example();
return 0;
}