实现:多态的综合案例

示例代码如下:解释都写在注释里面

#include<iostream>
#include<string>

using namespace std;

class Cpu { //定义cpu类
public:
	virtual void calculate() = 0;
};

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

class Memory {//定义Memory类

public:
	virtual void storage() = 0;
};

class InterCpu:public Cpu{ //封装一个InterCpu类
public:
	void calculate() {
		cout << "Intercpu正在计算" << endl;
	}

};

class InterVideoCard:public VideoCard { //封装一个InterCpu类
public:
	void display() {
		cout << "InterVideoCard正在显示" << endl;
	}
};

class InterMemory:public Memory{ //封装一个InterMemory类
public:
	void storage() {
		cout << "InterMem正在储存" << endl;
	}
};



class Computer {

public:

	Computer(Cpu * cpu,VideoCard * vc,Memory * mem ) {
		this->m_cpu = cpu;
		this->m_vc = vc;
		this->m_mem = mem;
	}
	~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;
		}
	}
	void Work() {
		m_cpu->calculate();
		m_mem->storage();
		m_vc->display();
	}
	
private:
	Cpu * m_cpu;
	VideoCard * m_vc;
	Memory * m_mem;
};

void test01() {
	Cpu * c1 = new InterCpu;
	VideoCard * vc1 = new InterVideoCard;
	Memory * m1= new InterMemory;
	
	Computer * com1 = new Computer(c1, vc1, m1);
	com1->Work();

	
}

int main() {
	test01();
	system("pause");
	return 0;
}
原文地址:https://www.cnblogs.com/zpchcbd/p/11871662.html