地球游戏的NPC罢了
唉今天一直打雷,不是很敢插电脑
多态案例--电脑组装 (是我睡了一觉就什么都不记得了)
零件类和具体的厂商零件是继承关系,电脑类和零件类只是嵌套关系【所以电脑类析构函数不需要虚析构】
#include<iostream>
using namespace std;
//抽象三个零件类
class Cpu {
public:
virtual void Calculate() = 0;
};
class Card {
public:
virtual void Display() = 0;
};
class Memory {
public:
virtual void Storage() = 0;
};
//电脑类(嵌套类)
class Computer {
public:
//构造函数传入三个零件指针
Computer(Cpu*cpu,Card*card,Memory*memory) {
m_cpu = cpu;
m_card = card;
m_memory = memory;
}
~Computer() {//析构函数释放三个指针内存
if (m_cpu != NULL) {
delete m_cpu;
m_cpu = NULL;
cout << "释放m_cpu" << endl;
}
if (m_card != NULL) {
delete m_card;
m_card = NULL;
cout << "释放m_card" << endl;
}
if (m_memory != NULL) {
delete m_memory;
m_memory = NULL;
cout << "释放m_memory" << endl;
}
}
void make() {
m_cpu->Calculate();//指针调用具体的函数
m_card->Display();
m_memory->Storage();
}
private://三个零件指针
Cpu* m_cpu;
Card* m_card;
Memory* m_memory;
};
//零件类的子类
class IntelCpu :public Cpu {
public:
void Calculate() {
cout << "Intel Cpu 开始计算啦" << endl;
}
};
class IntelCard :public Card {
public:
void Display() {
cout << "Intel Card 开始显示啦" << endl;
}
};
class IntelMemory :public Memory {
public:
void Storage() {
cout << "Intel Memory 开始存储啦" << endl;
}
};
//Lenon厂商
class LenonCpu :public Cpu {
public:
void Calculate() {
cout << "Lenon Cpu 开始计算啦" << endl;
}
};
class LenonCard :public Card {
public:
void Display() {
cout << "Lenon Card 开始显示啦" << endl;
}
};
class LenonMemory :public Memory {
public:
void Storage() {
cout << "Lenon Memory 开始存储啦" << endl;
}
};
void test01() {
cout <<endl<< "电脑1" << endl;
Cpu* intelcpu = new IntelCpu;//堆区开辟INTELCPU对象,COMPUTER创建CPU指针指向堆区
Card* card = new LenonCard;
Memory* memory = new IntelMemory;
Computer *com1=new Computer(intelcpu, card, memory);//堆区开辟Computer对象,返回COMPUTER类型指针
com1->make();//运行函数
delete com1;//释放内存
}
void test02() {
cout << endl << "电脑2" << endl;
Cpu* intelcpu = new LenonCpu;
Card* card = new LenonCard;
Memory* memory = new LenonMemory;
Computer* com2= new Computer(intelcpu, card, memory);
com2->make();
delete com2;
}
void test03() {
cout << endl << "电脑3" << endl;
Cpu* intelcpu = new IntelCpu;
Card* card = new IntelCard;
Memory* memory = new IntelMemory;
Computer* com3 = new Computer(intelcpu, card, memory);
com3->make();
delete com3;
}
int main() {
test01();
test02();
test03();
system("pause");
return 0;
}