C++多态案例-电脑组装

要求:

分析:

代码:

#include<iostream>
using namespace std;

//3个抽象零件类
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;
	}

	~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;
		}
	}
	void work()
	{
		m_cpu->calculate();
		m_vc->display();
		m_mem->storage();
	}

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的VideoCard开始运行了" << endl;
	}
};

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

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

	Computer* computer = new Computer(intelCpu, intelCard, intelMemory);
	computer->work();
}

int main() {
	test01();
}

  • 4
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值