20240420,多态案例--电脑组装

地球游戏的NPC罢了

唉今天一直打雷,不是很敢插电脑

多态案例--电脑组装  (是我睡了一觉就什么都不记得了)

零件类和具体的厂商零件是继承关系,电脑类和零件类只是嵌套关系【所以电脑类析构函数不需要虚析构】

#include<iostream>
using namespace std;
//抽象三个零件类
class Cpu  {
public:
	virtual void Calculate() = 0;
};
class Card  {
public:
	virtual void Display() = 0;
};
class Memory  {
public:
	virtual void Storage() = 0;
};
//电脑类(嵌套类)
class Computer {
public:
	//构造函数传入三个零件指针
	Computer(Cpu*cpu,Card*card,Memory*memory) {
		m_cpu = cpu;
		m_card = card;
		m_memory = memory;
	}
	~Computer() {//析构函数释放三个指针内存
		if (m_cpu != NULL) {
			delete m_cpu;
			m_cpu = NULL;
			cout << "释放m_cpu" << endl;
		}
		if (m_card != NULL) {
			delete m_card;
			m_card = NULL;
			cout << "释放m_card" << endl;
		}
		if (m_memory != NULL) {
			delete m_memory;
			m_memory = NULL;
			cout << "释放m_memory" << endl;
		}
	}
	void make() {
		m_cpu->Calculate();//指针调用具体的函数
		m_card->Display();
		m_memory->Storage();
	}
private://三个零件指针
	Cpu* m_cpu;
	Card* m_card;
	Memory* m_memory;
};
//零件类的子类
class IntelCpu :public Cpu {
public:
	void Calculate() {
		cout << "Intel Cpu 开始计算啦" << endl;
	}
};
class IntelCard :public Card {
public:
	void Display() {
		cout << "Intel Card 开始显示啦" << endl;
	}
};
class IntelMemory :public Memory {
public:
	void Storage() {
		cout << "Intel Memory 开始存储啦" << endl;
	}
};
//Lenon厂商
class LenonCpu :public Cpu {
public:
	void Calculate() {
		cout << "Lenon Cpu 开始计算啦" << endl;
	}
};
class LenonCard :public Card {
public:
	void Display() {
		cout << "Lenon Card 开始显示啦" << endl;
	}
};
class LenonMemory :public Memory {
public:
	void Storage() {
		cout << "Lenon Memory 开始存储啦" << endl;
	}
};
void test01() {
	cout <<endl<< "电脑1" << endl;
	Cpu* intelcpu = new IntelCpu;//堆区开辟INTELCPU对象,COMPUTER创建CPU指针指向堆区
	Card* card = new LenonCard;
	Memory* memory = new IntelMemory;
	Computer *com1=new Computer(intelcpu, card, memory);//堆区开辟Computer对象,返回COMPUTER类型指针
	com1->make();//运行函数
	delete com1;//释放内存
}
void test02() {
	cout << endl << "电脑2" << endl;
	Cpu* intelcpu = new LenonCpu;
	Card* card = new LenonCard;
	Memory* memory = new LenonMemory;
	Computer* com2= new Computer(intelcpu, card, memory);
	com2->make();
	delete com2;
}
void test03() {
	cout << endl << "电脑3" << endl;
	Cpu* intelcpu = new IntelCpu;
	Card* card = new IntelCard;
	Memory* memory = new IntelMemory;
	Computer* com3 = new Computer(intelcpu, card, memory);
	com3->make();
	delete com3;
}
int main() {
	test01();
	test02();
	test03();
	system("pause");
	return 0;
}

 

  • 6
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值