C++多态(2):电脑案例

电脑组装案例

在这里插入图片描述

#include<iostream>
using namespace std;
#include<string>

//抽象不同零件类
//抽象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* x_cpu, VideoCard* x_vc, Memory* x_mem) {
		cpu = x_cpu;
		vc = x_vc;
		mem = x_mem;
	}
	void work() {
		cpu->calculate();
		vc->display();
		mem->storage();
	}
	~Computer() {
		if (cpu != NULL) {
			delete cpu;
			cpu = NULL;
		}
		if (vc != NULL) {
			delete vc;
			vc = NULL;
		}
		if (mem != NULL) {
			delete mem;
			mem = NULL;
		}
	}
private:
	CPU * cpu;	//CPU零件指针
	VideoCard * vc;  //显卡零件指针
	Memory * mem;  //内存条零件指针
};
class LenovoCPU:public CPU{
public:
	virtual void calculate() {
		cout << "Lenovo的CPU开始计算了!" << endl;
	}
};
class LenovoVideoCard :public VideoCard {
public:
	virtual void display() {
		cout << "Lenovo的显卡开始计算了!" << endl;
	}
};
class LenovoVideoMemory :public Memory {
public:
	virtual void storage() {
		cout << "Lenovo的内存条开始计算了!" << endl;
	}
};
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;
	}
};
//主板
int main() {
	//第一台电脑零件
	CPU * intelCpu = new IntelCPU;
	VideoCard * intelCard = new IntelVideoCard;
	Memory * intelMem = new IntelMemory;
	//创建第一台电脑零件
	Computer * computer1 = new Computer(intelCpu, intelCard, intelMem);
	delete computer1;
	cout << "******************************************" << endl;
	cout << "第二台电脑开始组装工作!";
	Computer * computer2 = new Computer(new LenovoCPU, new IntelVideoCard, new IntelMemory);
	delete computer2;
	cout << "******************************************" << endl;
	cout << "第三台电脑开始组装工作!";
	Computer * computer3 = new Computer(new IntelCPU, new LenovoVideoCard, new IntelMemory);
	delete computer3;

	system("pause");
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值