学习笔记 C++ 多态 案例三 电脑组装

案例描述:

1.电脑主要组成部件为 CPU(用于计算),显卡(用于显示),内存条(用于存储)
2.将每个零件封装出抽象基类,并且提供不同的厂商生产不同的零件,例如Intel厂商和Lenovo厂商
3.创建电脑类提供让电脑工作的函数,并且调用每个零件工作的接口
4.测试时组装三台不同的电脑进行工作

#include<iostream>
using namespace std;
#include<string>
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 dowork()
	{
		m_cpu->calculate();
		m_vc->display();
		m_mem->storage();
	}
	~Computer()
	{
		if (m_cpu != NULL)
		{
			delete m_cpu;
			m_cpu = NULL;
		}
		if (m_vc != NULL)
		{
			delete m_vc;
			m_vc = NULL;
		}
		if (m_mem != NULL)
		{
			delete m_mem;
			m_mem = NULL;
		}
	}
private:
	CPU* m_cpu;
	VideoCard* m_vc;
	Memory* m_mem;
};
class IntelCPU :public CPU
{
	void calculate()
	{
		cout << "Intel的CPU开始计算了" << endl;
	}
};
class IntelVideoCard :public VideoCard
{
	void display()
	{
		cout << "Intel能够正常显示" << endl;
	}
};
class IntelMemory :public Memory
{
	void storage()
	{
			cout << "Intel能够正常存储" << endl;
	}
};
class LenovoCPU :public CPU
{
	void calculate()
	{
		cout << "Lenovo的CPU开始计算了" << endl;
	}
};
class LenovoVideoCard :public VideoCard
{
	void display()
	{
		cout << "Lenovo能够正常显示" << endl;
	}
};
class LenovoMemory :public Memory
{
	void storage()
	{
		cout << "Lenovo能够正常存储" << endl;
	}
};

void test()
{
	cout<<"第一台电脑开始工作:" << endl;
	CPU* cpu= new IntelCPU;
	VideoCard* vc= new IntelVideoCard;
	Memory* mem= new IntelMemory;
	Computer *computer1=new Computer(cpu, vc, mem);
	computer1->dowork();
	delete computer1;
	cout<<"-----------------------------------" << endl;
	cout << "第二台电脑开始工作:" << endl;
	Computer* computer2 = new Computer(new LenovoCPU, new IntelVideoCard, new LenovoMemory);
	computer2->dowork();
	delete computer2;
	cout << "-----------------------------------" << endl;
	cout << "第三台电脑开始工作:" << endl;
	Computer* computer3 = new Computer(new IntelCPU, new LenovoVideoCard, new LenovoMemory);
	computer3->dowork();
	delete computer3;
}
int main() 
{	
	test();
	system("pause");
 	return 0;
}

在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值