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

#include
using namespace std;

//抽象不同零件类
//抽象CPU类
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;
	}

	//提供工作的函数
	void work()
	{
		//让零件工作起来,调用接口
		m_cpu->calculate();
		m_vc->display();
		m_mem->storage();
	}

	//提供析构函数 释放3个电脑零件
	~Computer()
	{
		if (m_cpu != NULL)
		{
			delete m_cpu;
			m_cpu = NULL;
		}
	}

	//释放显卡零件
	~Computer()
	{
		if (m_vc != NULL)
		{
			delete m_vc;
			m_vc = NULL;
		}
	}

	//释放内存条零件
	~Computer()
	{
		if (m_mem != NULL)
		{
			delete m_mem;
			m_mem = NULL;
		}
	}

private:

	CPU* m_cpu;//CPU的零件指针
	VideoCard* m_vc;//显卡零件指针
	Memory* m_mem;//内存条零件指针
};

//具体厂商
//Intel厂商
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;
	}
};

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

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

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

void test01()
{
	//第一台电脑零件
	CPU* intelCpu = new IntelCPU;
	VideoCard* intelCard = new IntelVideoCard;
	Memory* intelMem = new IntelMemory;

	//创建第一台电脑
	Computer* computerl = new Computer(intelCpu, intelCard, intelMem);
	computerl->work();
	delete computerl;

}


int main()
{
	test01();

	system("puase");
	return 0;
}
仅个人看视频笔记与理解,如有误可指出谢谢

你可能感兴趣的:(c++)