C++学习Day07之多态案例

本文通过C++代码展示了如何使用多态和虚函数创建可重用的电脑类,其中包含不同厂商的CPU、VideoCard和Memory组件。test01函数创建并操作了两台具有不同硬件配置的电脑。
摘要由CSDN通过智能技术生成


一、程序及输出

computer类包含了CPU、VideoCard和Memory三个基类的指针成员。
在test01函数中,创建了两台电脑,每台电脑由不同厂商的CPU、VideoCard和Memory组成。
通过调用doWork函数,每台电脑会分别执行CPU的calculate、VideoCard的display和Memory的storage操作。

#include<iostream>
using namespace std;

//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 * cpu, VideoCard * vc, Memory * mem)
	{
		cout << "电脑构造调用" << endl;
		this->m_Cpu = cpu;
		this->m_Vc = vc;
		this->m_Mem = mem;
	}

	void doWork()
	{
		this->m_Cpu->calculate();
		this->m_Vc->display();
		this->m_Mem->storage();
	}

	~computer()
	{
		cout << "电脑析构调用" << endl;
		if (this->m_Cpu)
		{
			delete this->m_Cpu;
			this->m_Cpu = NULL;
		}
		if (this->m_Vc)
		{
			delete this->m_Vc;
			this->m_Vc = NULL;
		}
		if (this->m_Mem)
		{
			delete this->m_Mem;
			this->m_Mem = NULL;
		}
	}

	CPU * m_Cpu;
	VideoCard * m_Vc;
	Memory * m_Mem;
};


//inter厂商
class intelCPU :public CPU
{
public:
	void calculate()
	{
		cout << "intelCPU开始计算了" << endl;
	}
};

class intelVideoCard :public VideoCard
{
public:
	void display()
	{
		cout << "intel 显卡开始显示了" << endl;
	}

};
class intelMemory :public Memory
{
public:
	void storage()
	{
		cout << "intel 内存条开始存储了" << endl;
	}
};


//Lenovo 厂商
class LenovoCPU :public CPU
{
public:
	void calculate()
	{
		cout << "Lenovo CPU开始计算了" << endl;
	}
};

class LenovoVideoCard :public VideoCard
{
public:
	void display()
	{
		cout << "Lenovo 显卡开始显示了" << endl;
	}

};
class LenovoMemory :public Memory
{
public:
	void storage()
	{
		cout << "Lenovo 内存条开始存储了" << endl;
	}
};


void test01()
{
	cout << "第一台电脑组成:" << endl;

	CPU * intelCpu = new intelCPU;
	VideoCard * lenovoVC = new LenovoVideoCard;
	Memory * lenovoMem = new LenovoMemory;

	computer c1(intelCpu, lenovoVC, lenovoMem);

	c1.doWork();

    cout << "-------------------------" << endl;
	cout << "第二台电脑组成:" << endl;

	CPU * intelCpu2 = new LenovoCPU;
	VideoCard * lenovoVC2 = new intelVideoCard;
	Memory * lenovoMem2 = new intelMemory;

	computer c2(intelCpu2, lenovoVC2, lenovoMem2);
	c2.doWork();
}

int main(){
	test01();
	system("pause");
	return EXIT_SUCCESS;
}

输出:
在这里插入图片描述


二、分析与总结

多态、虚函数、继承的综合使用

  • 4
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值