这个是承接上一篇文章的
这里我就不多描述了 ,大家直接看代码深入了解吧:
#include<iostream>
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* cpu, videocard* vc, memory* mem)
{
m_cpu = cpu;
m_vc = vc;
m_mem = mem;
}
void work()
{
m_cpu->calculate();
m_vc->display();
m_mem->storage();
}
private:
cpu* m_cpu;
videocard* m_vc;
memory* m_mem;
};
//intel组件
class intelcpu :public cpu
{
public:
void calculate()
{
cout << "intel的cpu开始计算了" << endl;
}
};
class intelvideocard :public videocard
{
public:
void display()
{
cout << "intel的显卡开始显示了" << endl;
}
};
class intelmemory :public memory
{
public:
void storage()
{
cout << "intel的内存条开始储存了" << endl;
}
};
//lenovo组件
class lenovocpu :public cpu
{
public:
void calculate()
{
cout << "lenovo的cpu开始计算了" << endl;
}
};
class lenovovideocard :public videocard
{
public:
void display()
{
cout << "lenovo的显卡开始显示了" << endl;
}
};
class lenovomemory :public memory
{
public:
void storage()
{
cout << "lenovo的内存条开始储存了" << endl;
}
};
void test01()
{
//制造部件
cpu* cpu1 = new intelcpu;
videocard* vc1 = new intelvideocard;
memory* mem1 = new intelmemory;
cpu* cpu2 = new lenovocpu;
videocard* vc2 = new lenovovideocard;
memory* mem2= new lenovomemory;
//组装电脑
computer* computer1 = new computer(cpu1, vc1, mem1);
computer* computer2 = new computer(cpu2, vc2, mem2);
computer* computer3 = new computer(cpu1, vc2, mem1);
//封装指针数组
computer* arr[3] = { computer1,computer2,computer3 };
//执行工作函数
for (int i = 0; i < 3; i++)
{
arr[i]->work();
cout << "------------" << endl;
}
}
int main()
{
test01();
system("pause");
return 0;
}