c++学习笔记_多态案例3-组装电脑(来自哔站黑马程序员-c++教学视频)

该代码示例展示了如何使用C++进行面向对象编程,通过抽象基类定义电脑的CPU、显卡和内存条,然后由Intel和Lenovo的具体类继承这些抽象类,实现多态。Computer类通过指针组合不同的硬件部件,实现了不同品牌电脑的工作模拟。在main函数中,创建并测试了三台具有不同配置的电脑,演示了对象组合和动态绑定的概念。
摘要由CSDN通过智能技术生成

案例:

 分析:

#include<iostream>
using namespace std;

//电脑组成:cpu、显卡、内存条

//抽象出每个零件的类
class CPU
{
public:
	virtual void calculate() = 0;
	virtual ~CPU()
	{

	}
};

class VideoCard
{
public:
	virtual void display() = 0;
	virtual ~VideoCard()
	{

	}
};

class Memory
{
public:
	virtual void storage() = 0;
	virtual ~Memory()
	{

	}
};

//具体厂商类
class IntelCpu :public CPU
{
public:
	virtual void calculate()
	{
		cout << "Intel的CPU开始计算了!" << endl;
	}
};


class IntelVideoCard :public VideoCard
{
public:
	virtual void display()
	{
		cout << "Intel显卡开始显示!" << endl;
	}
};

class IntelMemory :public Memory
{
public:
	virtual void storage()
	{
		cout << "Intel内存开始存储!" << endl;
	}
};

class LenovoCpu:public CPU
{
public:
	virtual void calculate()
	{
		cout << "Lenovo的CPU开始计算了!" << endl;
	}
};

class LenovoVideoCard :public VideoCard
{
public:
	virtual void display()
	{
		cout << "Lenovo显卡开始显示!" << endl;
	}
};

class LenovoMemory:public Memory
{
public:
	virtual void storage()
	{
		cout << "Lenovo内存开始存储!" << endl;
	}
};



//电脑类,组装不同品牌零件
class Computer
{
public:
	Computer(CPU* cpu,  VideoCard* vc, Memory* memory)
	{
		cout << "Computer组装" << endl;
		m_cpu = cpu;
		m_vc = vc;
		m_moemory = memory;
	}
	//工作函数
	void doWork()
	{
		m_cpu->calculate();
		m_vc->display();
		m_moemory->storage();
	}
	//提供析构函数 释放3个零件
	~Computer()
	{
		if (m_cpu != NULL)
		{
			delete m_cpu;
			m_cpu = NULL;
		}

		if (m_vc != NULL)
		{
			delete m_vc;
			m_vc = NULL;
		}

		if (m_moemory != NULL)
		{
			delete m_moemory;
			m_moemory = NULL;
		}
	}
private:
	CPU* m_cpu;//cpu零件指针
	VideoCard* m_vc;//显卡零件指针
	Memory* m_moemory;//内存零件指针
};


void test01()
{
	CPU* intelCpu = new IntelCpu;
	VideoCard* intelVideoCard = new IntelVideoCard;
	Memory* intelMemory = new IntelMemory;

	cout << "第一台电脑开始工作" << endl;
	//创建第一台电脑
	Computer* computer1 = new Computer(intelCpu, intelVideoCard, intelMemory);
	computer1->doWork();
	delete computer1;

	cout << "--------------------------" << endl;
	cout << "第二台电脑开始工作" << endl;
	//创建第一台电脑
	Computer* computer2 = new Computer(new LenovoCpu, new LenovoVideoCard, new LenovoMemory);
	computer2->doWork();
	delete computer2;

	cout << "--------------------------" << endl;
	cout << "第三台电脑开始工作" << endl;
	Computer* computer3 = new Computer(new LenovoCpu, new IntelVideoCard,new LenovoMemory);
	computer3->doWork();
	delete computer3;
}

int main()
{
	test01();
	system("pause");
	return 0;
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值