c++学习之多态案例--电脑组装

代码示例

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

/*********************器件基类,不用作什么事,让子类派生重写************************/
//cpu基类
class Cpu 
{
	public:
		virtual void calculate() = 0;
};

//VideoCard基类
class VideoCard
{
	public:
		virtual void display() = 0;
};

//Memory基类
class Memory 
{
	public:
		virtual void storage() = 0;
};

/*********************派生类,不同厂商的器件对基类器件进行重写************************/
/********Inter*********/
//cpu基类
class InterCpu:public Cpu
{
	public:
		void calculate()
		{
			cout << "inter cpu is doing work" <<endl;
		}
};

//VideoCard基类
class InterVideoCard:public VideoCard
{
	public:
		void display()
		{
			cout << "inter videoCard is doing work" <<endl;
		}
};

//Memory 基类
class InterMemory:public Memory
{
	public:
		void storage()
		{
			cout << "inter memory is doing work" <<endl;
		}
};
/********lenovo*********/
//cpu基类
class lenovoCpu :public Cpu
{
	public:
		void calculate()
		{
			cout << "lenovo cpu is doing work" <<endl;
		}
};

//VideoCard基类
class lenovoVideoCard:public VideoCard
{
	public:
		void display()
		{
			cout << "lenovo videoCard is doing work" <<endl;
		}
};

//Memory基类
class lenovoMemory :public Memory
{
	public:
		void storage()
		{
			cout << "lenovo memory is doing work" <<endl;
		}
};
/***************************电脑类*********************************/
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();
		}
		 ~Computer()
		{
			if(m_cpu)
			{
				delete m_cpu;
				m_cpu = NULL;
			}

			if(m_vc)
			{
				delete m_vc;
				m_vc = NULL;
			}
			
			if(m_mem)
			{
				delete m_mem;
				m_mem = NULL;
			}
		}
	private:
		Cpu *m_cpu;
		VideoCard *m_vc;
		Memory *m_mem;
};

void test()
{
	//第一台电脑 采用inter零件
	Cpu *Intercpu = new InterCpu;
	VideoCard *Intervc = new InterVideoCard;
	Memory *Intermem = new InterMemory;
	Computer *c1 = new Computer(Intercpu,Intervc,Intermem);
	c1->work();
	cout <<"--------------------------------------" <<endl;
	//第二台电脑 采用lenovo零件
	Computer *c2 = new Computer(new lenovoCpu,new lenovoVideoCard,new lenovoMemory);
	c2->work();
	
	delete c1;
	delete c2;

}
int main()
{
	test();
    return 0; 
}

输出结果
在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

<( ̄︶ ̄)Okay.

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值