C++——多态经典案例(一)组装电脑

案例:小明打算买两台组装电脑,假设电脑零部件包括CPU、GPU和内存组成。

一台电脑使用intel的CPU、GPU和内存条

一台电脑使用Huawei的CPU、GPU和Intel的内存条

分析:使用多态进行实现

将CPU、GPU和内存条定义为抽象类,内部分别定义其对应功能的纯虚函数

Intel的CPU继承CPU,并实现其内部的纯虚函数(calculate)

Intel的GPU继承GPU,并实现其内部的纯虚函数(display)

Intel的MEMORY继承MEMORY,并实现其内部的纯虚函数(memory)

同样华为也一样继承CPU、GPU和MEMORY并实现对应的纯虚函数

封装一个Computer类,包含CPU、GPU和MEMORY,其成员属性为CPU、GPU和MEMORY的指针

内部有个work方法,用于调用CPU、GPU和MEMORY对应的方法

最后小明通过Computer类进行组装自己的电脑,并运行

cpp 复制代码
#include<iostream>
class CPU 
{
public:
	virtual void calculate() = 0;
};

class GPU
{
public:
	virtual void display() = 0;
};

class MEMORY
{
public:
	virtual void memory() = 0;
};


class Computer 
{
public:
	Computer(CPU *cpu,GPU *gpu,MEMORY *memory)
	{
		m_cpu = cpu;
		m_gpu = gpu;
		m_memory = memory;
	}

	void work() 
	{
		m_cpu->calculate();
		m_gpu->display();
		m_memory->memory();
	}

	~Computer()
	{
		if (m_cpu != NULL) 
		{
			delete m_cpu;
			m_cpu = NULL;
		}
		if (m_gpu != NULL)
		{
			delete m_gpu;
			m_gpu = NULL;
		}
		if (m_memory != NULL)
		{
			delete m_memory;
			m_memory = NULL;
		}
	}

private:
	CPU *m_cpu;
	GPU *m_gpu;
	MEMORY *m_memory;
};


class IntelCPU :public CPU
{
public:
	virtual void calculate()
	{
		std::cout << "IntelCPU is calculate..." << std::endl;
	}
};
class IntelGPU :public GPU
{
public:
	virtual void display()
	{
		std::cout << "IntelGPU is display..." << std::endl;
	}
};
class IntelMEMORY :public MEMORY
{
public:
	virtual void memory()
	{
		std::cout << "IntelMEMORY is memory..." << std::endl;
	}
};



class HuaweiCPU :public CPU
{
public:
	virtual void calculate()
	{
		std::cout << "HuaweiCPU is calculate..." << std::endl;
	}
};
class HuaweiGPU :public GPU
{
public:
	virtual void display()
	{
		std::cout << "HuaweiGPU is display..." << std::endl;
	}
};
class HuaweiMEMORY :public MEMORY
{
public:
	virtual void memory()
	{
		std::cout << "HuaweiMEMORY is memory..." << std::endl;
	}
};




int main(int argc,char **argv) 
{
	CPU *my_CPU = new IntelCPU;
	GPU *my_GPU = new IntelGPU;
	MEMORY *my_memory = new IntelMEMORY;

	Computer *my_computer = new Computer(my_CPU, my_GPU, my_memory);
	my_computer->work();
	delete my_computer;


	Computer* my_computer_2 = new Computer(new HuaweiCPU,new HuaweiGPU,new IntelMEMORY);
	my_computer_2->work();
	return 0;
}

运行效果:

相关推荐
小马爱打代码1 天前
Spring AI 实战:Agent 基础搭建与核心能力解析
java·人工智能·spring
csdn2015_1 天前
springboot task
java·spring boot·后端
2301_790300961 天前
C++中的命令模式
开发语言·c++·算法
2301_822376941 天前
C++中的解释器模式
开发语言·c++·算法
czlczl200209251 天前
Spring Boot :如何高性能地在 Filter 中获取响应体(Response Body)
java·spring boot·后端
爱学习的阿磊1 天前
C++代码冗余消除
开发语言·c++·算法
sg_knight1 天前
抽象工厂模式(Abstract Factory)
java·python·设计模式·抽象工厂模式·开发
春日见1 天前
win11 分屏设置
java·开发语言·驱动开发·docker·单例模式·计算机外设
2301_780029041 天前
支付宝sdk导入错误
java·开发语言·maven
十年编程老舅1 天前
冲刺米哈游|游戏开发一面面经(26 届
linux·c++·米哈游