多态案例——电脑

#include<iostream>

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 *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 != NULL){
				delete m_cpu;
				m_cpu = NULL;	
			}
			
			if(m_vc != NULL){
				delete m_vc;
				m_vc = NULL;	
			}
			
			if(m_mem != NULL){
				delete m_mem;
				m_mem = NULL;	
			}
		}
		
	private:
		CPU *m_cpu;
		VideoCard *m_vc;
		Memory *m_mem;
};

//Interl 
class InterlCPU : public CPU{
	public:
		virtual void calculate(){		
		cout << "Interl的CPU开始计算" << endl; 
		}
};

class InterlVideoCard : public VideoCard{
	public:
		virtual void display(){		
		cout << "Interl的ViderCard开始显示" << endl; 
		}
};

class InterlMemory : public Memory{
	public:
		virtual void storage(){		
		cout << "Interl的Memory开始存储" << endl; 
		}
};

//Lenovo
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 test(){
	CPU * interlCpu = new InterlCPU;
	VideoCard * interlCard = new InterlVideoCard;
	Memory * interlMem = new InterlMemory;
	
	Computer * computer1 = new Computer(interlCpu, interlCard, interlMem);
	computer1 -> work();
	delete computer1;
	
	cout << "---------------------" << endl;
	CPU * interlCpu2 = new InterlCPU;
	VideoCard * lenovolCard2 = new LenovoVideoCard;
	Memory * interlMem2 = new InterlMemory;
	
	Computer * computer2 = new Computer(interlCpu2, lenovolCard2, interlMem2);
	computer2 -> work();
	delete computer2;	
	
	cout << "---------------------" << endl;
	CPU * LenovoCpu3 = new LenovoCPU;
	VideoCard * LenovoCard3 = new LenovoVideoCard;
	Memory * LenovoMem3 = new LenovoMemory;
	
	Computer * computer3 = new Computer(LenovoCpu3, LenovoCard3, LenovoMem3);
	computer2 -> work();
	delete computer2;	
	
}

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

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

高阔843

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

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

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

打赏作者

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

抵扣说明:

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

余额充值