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

案例:

 分析:

#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;
}

猜你喜欢

转载自blog.csdn.net/qq_26572229/article/details/129000240