按照要求利用多态的方法,设计CPU,显卡,内存父类,为纯虚函数,然后各自生成联想和Intel的分类部件
建立computer类,为指向CPU,显卡,内存父类的指针
在测试阶段,用的是堆区创建各部件,再用各部件组成电脑,记得堆区数据销毁即可
#include <iostream>
#include <string>
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* a, videocard* b, memory* c) {
m_cpu = a;
m_vc = b;
m_mer = c;
}
void dowork() {
m_cpu->calculate();
m_vc->display();
m_mer->storage();
};
~computer(){
if (m_cpu != NULL) {
delete m_cpu;
m_cpu = NULL;
}
if (m_vc != NULL) {
delete m_vc;
m_vc = NULL;
}
if (m_mer != NULL) {
delete m_mer;
m_mer = NULL;
}
}
private:
CPU* m_cpu;
videocard* m_vc;
memory* m_mer;
};
class IntelCPU :public CPU {
public:
virtual void calculate() {
cout << "Intel厂商的CPU开始工作" << endl;
};
};
class Intelvideocard :public videocard {
public:
virtual void display() {
cout << "Intel厂商的videocard开始工作" << endl;
};
};
class Intelmemory :public memory {
public:
virtual void storage() {
cout << "Intel厂商的内存条开始工作" << endl;
};
};
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 test01() {
//创造零件
CPU* intelcpu = new LenovoCPU;
videocard* intelcard = new Intelvideocard;
memory* intelmemory = new Intelmemory;
computer* computer1 = new computer(intelcpu, intelcard, intelmemory);
computer1->dowork();
delete computer1;
}
int main() {
test01();
system("pause");
return 0;
}