多态——组装电脑

按照要求利用多态的方法,设计CPU,显卡,内存父类,为纯虚函数,然后各自生成联想和Intel的分类部件
建立computer类,为指向CPU,显卡,内存父类的指针
在测试阶段,用的是堆区创建各部件,再用各部件组成电脑,记得堆区数据销毁即可

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


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* a, videocard* b, memory* c) {
		m_cpu = a;
		m_vc = b;
		m_mer = c;
	}
	void dowork() {
		m_cpu->calculate();
		m_vc->display();
		m_mer->storage();
	};
	~computer(){
		if (m_cpu != NULL) {
			delete m_cpu;
			m_cpu = NULL;
		}
		if (m_vc != NULL) {
			delete m_vc;
			m_vc = NULL;
		}
		if (m_mer != NULL) {
			delete m_mer;
			m_mer = NULL;
		}
	}
private:
	CPU* m_cpu;
	videocard* m_vc;
	memory* m_mer;
};

class IntelCPU :public CPU {
public:
	virtual void calculate() {
		cout << "Intel厂商的CPU开始工作" << endl;
	};
};
class Intelvideocard :public videocard {
public:
	virtual void display() {
		cout << "Intel厂商的videocard开始工作" << 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厂商的videocard开始工作" << endl;
	};
};
class Lenovomemory :public memory {
public:
	virtual void storage() {
		cout << "Lenovo厂商的memory开始工作" << endl;
	};
};
void test01() {
	//创造零件
	CPU* intelcpu = new LenovoCPU;
	videocard* intelcard = new Intelvideocard;
	memory* intelmemory = new Intelmemory;

	computer* computer1 = new computer(intelcpu, intelcard, intelmemory);
	computer1->dowork();
	delete computer1;
}
int main() {
	test01();
	system("pause");
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值