多态综合运用,电脑组装

这个是承接上一篇文章的

多态 纯虚函数应用 子类两种调用方式_Koi279的博客-CSDN博客一个例子帮助了解多态https://blog.csdn.net/qq_64360901/article/details/122895719?spm=1001.2014.3001.5501

这里我就不多描述了 ,大家直接看代码深入了解吧:

#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;
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Koi279

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值