电脑组装

  1. #include <iostream>
  2. #include <string>
  3. using namespace std;
  4. class CPU { public: virtual void Calc() = 0; };
  5. class GPU { public: virtual void Display() = 0; };
  6. class RAM { public: virtual void Storge() = 0; };
  7. class Computer {
  8. public:
  9. Computer(CPU* cpu, GPU* gpu, RAM* ram) { //将组成电脑的三个组件传进来
  10. this->m_CPU = cpu; //成员组件将会是传进来的内容
  11. this->m_GPU = gpu;
  12. this->m_RAM = ram;
  13. }
  14. void Work() { //工作函数调用
  15. m_CPU->Calc();
  16. m_GPU->Display();
  17. m_RAM->Storge();
  18. }
  19. ~Computer() { //自身的析构释放堆数据
  20. if (m_CPU != NULL) {
  21. delete m_CPU;
  22. m_CPU = NULL;
  23. }else if (m_GPU != NULL) {
  24. delete m_GPU;
  25. m_GPU = NULL;
  26. }
  27. else if(m_RAM != NULL) {
  28. delete m_RAM;
  29. m_RAM = NULL;
  30. }
  31. }
  32. private:
  33. CPU* m_CPU;
  34. GPU* m_GPU;
  35. RAM* m_RAM;
  36. };
  37. class IntelCPU:public CPU { //Intel的CPU必须继承CPU的纯虚函数
  38. public:
  39. void Calc() {
  40. cout << "Intel CPU Processing" << endl;
  41. }
  42. };
  43. class IntelGPU :public GPU {
  44. public:
  45. void Display() {
  46. cout << "Intel GPU Displaying Images" << endl;
  47. }
  48. };
  49. class IntelRAM:public RAM{
  50. public:
  51. void Storge() {
  52. cout << "Intel RAM Storging Data" << endl;
  53. }
  54. };
  55. class DellRAM :public RAM {
  56. public:
  57. void Storage() {
  58. cout << "Dell RAM Storageing Data" << endl;
  59. }
  60. };
  61. class DellGPU :public GPU {
  62. public:
  63. void Display() {
  64. cout << "Dell GPU Displaying Images" << endl;
  65. }
  66. };
  67. class DellCPU :public CPU {
  68. public:
  69. void Calc() {
  70. cout << "Dell CPU Processing" << endl;
  71. }
  72. };
  73. void example(){
  74. CPU* cpu = new IntelCPU;//CPU使用IntelCPU进行创建
  75. GPU* gpu = new DellGPU;//在堆区创建GPU
  76. RAM* ram = new IntelRAM;
  77. Computer *PC1 = new Computer(cpu, gpu, ram);
  78. //在堆区创建电脑,然后在堆区进行组装
  79. PC1->Work();
  80. delete PC1;//释放掉
  81. }
  82. int main() {
  83. example();
  84. return 0;
  85. }