黑马程序员C++教程从0到1入门编程60类与对象--多态案例子3电脑组装具体案例

  • c++中使用多态实现电脑组装具体案例
    • 例子

c++中使用多态实现电脑组装具体案例

例子

#include <iostream>
#include<string>
using namespace std;
//多态案列3-电脑组装
#if 1
//抽象不同零件类
//抽象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*video, memory*menory)
	{
		a = cpu;
		b = video;
		c = menory;
	}

	//提供析构函数
	~computer()
	{
		//释放cpu零件
		if (a != NULL)
		{
			delete a;
			a = NULL;
		}
		//释放显卡零件
		if (b != NULL)
		{
			delete b;
			b = NULL;
		}
		//释放内存条零件
		if (c != NULL)
		{
			delete c;
			c = NULL;
		}
	}


	//提供工作的函数
	void work()
	{
		//让零件工作起来,调用接口
		a->calculate();
		b->display();
		c->storage();
	}

private:
	cpu *a;//cpu零件指针
	videocard*b;//显卡指针
	memory*c;
};

//具体厂商
//intel厂商
class intelcpu :public cpu
{
	virtual void calculate()
	{
		cout << "intel的cpu开始计算啦" << endl;
	}
};

class intelvedio :public videocard
{
	virtual void display()
	{
		cout << "intel的显卡开始计算啦" << endl;
	}
};

class intelmem :public memory
{
	virtual void storage()
	{
		cout << "intel的内存条开始计算啦" << endl;
	}
};


//lenovo
class lenovocpu :public cpu
{
	virtual void calculate()
	{
		cout << "lenovo的cpu开始计算啦" << endl;
	}
};

class lenovovedio :public videocard
{
	virtual void display()
	{
		cout << "lenovo的显卡开始计算啦" << endl;
	}
};

class lenovomem :public memory
{
	virtual void storage()
	{
		cout << "lenovo的内存条开始计算啦" << endl;
	}
};

void test01()
{
	//第一台电脑零件
	cpu*intcpu = new intelcpu;
	videocard*intelvideocard = new intelvedio;
	memory*menory = new intelmem;


	//第一台电脑
	computer *conputer1=new computer(intcpu, intelvideocard, menory);
	conputer1->work();
	delete conputer1;

	//第二台电脑
	/*cpu*intcpu1 = new lenovocpu;
	videocard*intelvideocard1 = new lenovovedio;
	memory*menory1 = new lenovomem;
*/
	computer *conputer2 = new computer(new lenovocpu, new lenovovedio, new lenovomem);
	conputer2->work();
	delete conputer2;

}

#endif // 1



int main()
{
	test01();
	///test02();
	
	system("pause");
	return 0;
}


更多推荐

黑马程序员C++教程从0到1入门编程60类与对象--多态案例子3电脑组装具体案例