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

# include<iostream>
# include<string>

using namespace std;

//抽象的CPU
class CPU
{
public:
	virtual void caculate() = 0;
};
//抽象的显卡
class GraphicsCard
{
public:
	virtual void show() = 0;
};

//抽象的内存条
class RAM
{
public:
	virtual void storage() = 0;
};

//电脑类
class Compute
{
public:
	Compute(CPU* cpu, GraphicsCard* gc, RAM* ram)
	{
		m_cpu = cpu;
		m_gc = gc;
		m_ram = ram;
	}

	void work()
	{
		m_cpu->caculate();
		m_gc->show();
		m_ram->storage();
	}
	~Compute()
	{
		if (m_cpu != NULL)
		{
			delete m_cpu;
			m_cpu = NULL;
		}

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

		if (m_ram != NULL)
		{
			delete m_ram;
			m_ram = NULL;
		}
	}
private:
	CPU* m_cpu;
	GraphicsCard* m_gc;
	RAM* m_ram;
};
class IntelCPU :public CPU
{
	void caculate()
	{
		cout << "Intel的GPU开始计算" << endl;
	}
};

class IntelGC :public GraphicsCard
{
	void show()
	{
		cout << "Intel的显卡开始显示" << endl;
	}
};

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

class LenovoCPU :public CPU
{
	void caculate()
	{
		cout << "Lenovo的GPU开始计算" << endl;
	}
};

class LenovoGC :public GraphicsCard
{
	void show()
	{
		cout << "Lenovo的显卡开始显示" << endl;
	}
};

class LenovoRAM :public RAM
{
	void storage()
	{
		cout << "Lenovo的RAM开始存储" << endl;
	}
};

void test01()
{
	//第一台电脑零件
	CPU* intelCpu = new IntelCPU;
	GraphicsCard* intelGc = new IntelGC;
	RAM* intelRam = new IntelRAM;

	//创建第一台电脑
	Compute* computer1 = new Compute(intelCpu, intelGc, intelRam);
	computer1->work();
	delete computer1;
}


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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值