C++学习笔记19,C++核心编程模板

20 篇文章 0 订阅
7 篇文章 0 订阅

多态案例三 —— 电脑组装

电脑主要组成部件为CPU(用于计算),显卡(用于显示),内存条(用于存储)

将每个零件封装出抽象基类,并且提供不同的厂商生产不同的零件,例如Intel厂商和Lenovo厂商

创建电脑类提供让电脑工作的函数,并且调用每个零件工作的接口
测试时组装三台不同的电脑进行工作

//每个零件的抽象类
class CPU
{
public :
	virtual void Calculate() = 0;
};
class GPU
{
public :
	virtual void Display() = 0;
};
class RAM
{
public :
	virtual void Storage() = 0;  
};

//Inter厂商的零件
class InterCPU : public CPU
{
public:
	void Calculate()
	{
		cout << "Inter的CPU开始计算" << endl;
	}
};
class InterGPU : public GPU
{
public :
	void Display()
	{
		cout << "Inter的GPU开始显示" << endl;
	}
};
class InterRAM : public RAM
{
public :
	void Storage()
	{
		cout << "Inter的RAM开始存储" << endl;
	}
};

//Lenovo厂商的零件
class LenovoCPU : public CPU
{
public:
	void Calculate()
	{
		cout << "Lenovo的CPU开始计算" << endl;
	}
};
class LenovoGPU : public GPU
{
public:
	void Display()
	{
		cout << "Lenovo的GPU开始显示" << endl;
	}
};
class LenovoRAM : public RAM
{
public:
	void Storage()
	{
		cout << "Lenovo的RAM开始存储" << endl;
	}
};

//电脑类
class Computer
{
private :
	CPU* m_CPU; //抽象类不能实例化,但是可以利用指针指向子类对象
	GPU* m_GPU;
	RAM* m_RAM;
public :
	Computer(CPU* cpu, GPU* gpu, RAM* ram)
	{
		m_CPU = cpu;
		m_GPU = gpu;
		m_RAM = ram;
	}
	~Computer()
	{
		if (m_CPU != NULL)
		{
			delete m_CPU;
			m_CPU = NULL;
		}
		if (m_GPU != NULL)
		{
			delete m_GPU;
			m_GPU = NULL;
		}
		if (m_RAM != NULL)
		{
			delete m_RAM;
			m_RAM = NULL;
		}
	}
	void DoWork()
	{
		m_CPU->Calculate();
		m_GPU->Display();
		m_RAM->Storage();
	}
};

void test53()
{
	Computer c1(new InterCPU, new InterGPU, new InterRAM);
	c1.DoWork();

	cout << "-----------------------" << endl;

	Computer *c2 = new Computer(new LenovoCPU, new LenovoGPU, new LenovoRAM);
	c2->DoWork();
	delete c2;
	c2 = NULL;

	cout << "-----------------------" << endl;

	CPU* cpu = new InterCPU;
	GPU* gpu = new InterGPU;
	RAM* ram = new InterRAM;
	Computer c3(cpu, gpu, ram);
	c3.DoWork();

	cout << "-----------------------" << endl;

	CPU* cpu2 = new InterCPU;
	GPU* gpu2 = new InterGPU;
	RAM* ram2 = new InterRAM;
	Computer *c4 = new Computer(cpu2, gpu2, ram2);
	c4->DoWork();
	delete c4;
	c4 = NULL;
}

void main53()
{
	test53();
	system("pause");
}

(哔哩哔 哩黑马程序员 C++教程 学习笔记,如有侵权请联系删除)

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值