c++多态的小例子

#include<iostream>
using namespace std;
#include<string>
//关于多态编程思想
class CPU//抽象类:无法实例化对象
{
public:
	virtual void calculate() = 0;
};
class Display
{
public:
	virtual void disp() = 0;
};
class Memonry
{
public:
	virtual void memon() = 0;
};

class InterCPU :public CPU//子类必须重写父类抽象方法,否则也为抽象类
{
public:
	void calculate()
	{
		cout << "Inter牌CPU正在计算" << endl;
	}
};

class InterDisplay :public Display
{
public:
	void disp()
	{
		cout << "Inter牌显卡正在工作" << endl;
	}
};

class InterMemory : public Memonry
{
public:
	void memon()
	{
		cout << "Inter牌内存条正在存储" << endl;
	}
};

class LenovoCPU :public CPU
{
public:
	void calculate()
	{
		cout << "Lenovo牌CPU正在计算" << endl;
	}
};

class LenovoDisplay :public Display
{
public:
	void disp()
	{
		cout << "Lenovo牌显卡正在工作" << endl;
	}
	
};

class LenovoMemory : public Memonry
{
public:
	void memon()
	{
		cout << "Lenovo牌内存条正在存储" << endl;
	}
};

class computer
{
public:
	computer(CPU *C,Display *D,Memonry *M)//构造函数,初始化类变量
	{
		c = C;
		d = D;
		m = M;
        c->calculate();
		d->disp();
		m->memon();
	}
	~computer()//析构,释放堆区代码
	{
		if (c != NULL)
		{
			delete c;
			c = NULL;
		}
		if (d != NULL)
		{
			delete d;
			d = NULL;
		}
		if (m != NULL)
		{
			delete m;
			m = NULL;
		}
	}
private:
	CPU* c;
	Display* d;
	Memonry* m;
};
int main()
{
	//父类的饮用和指针都可以直接指向子类对象
	//由于子类开辟到堆区,所以父类指针在释放的时候无法调用到子类的析构函数
	//解决办法:将父类的析构函数改为虚析构函数或者纯虚析构函数(纯虚析构函数在类外一定要实现)
	computer c(new LenovoCPU,new InterDisplay,new LenovoMemory);
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值