电脑组装案例描述:
电脑主要组成部件为 CPU(用于计算),显卡(用于显示),内存条(用于存储)
功能实现:
将每个零件封装出抽象基类,并且提供不同的厂商生产不同的零件,例如Intel厂商和Lenovo厂商
创建电脑类提供让电脑工作的函数,并且调用每个零件工作的接口
测试时组装三台不同的电脑进行工作
#include <iostream>
using namespace std;
class CPU{
//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){
//抽象类不能实体化对象,只能用指针了
m_cpu = cpu;
m_vc = vc;
m_mem = mem;
}
void work(){
m_cpu->calculate(); //让零件工作起来,调用接口
m_vc->display();
m_mem->storage();
}
~Computer(){
//提供析构函数 释放3个电脑零件
if (m_cpu != NULL){
//释放CPU零件
delete m_cpu;
m_cpu = NULL;//因为不置空,这个指针还可以访问这个内存,会造成内存泄漏(这就叫野指针),经典的UAF攻击就是利用的野指针
}
if (m_vc != NULL){
//释放显卡零件
delete m_vc;
m_vc = NULL;
}
if (m_mem != NULL){
//释放内存条零件
delete m_mem;
m_mem = NULL;
}
}
private:
CPU* m_cpu; //CPU的零件指针
VideoCard* m_vc; //显卡零件指针
Memory* m_mem; //内存条零件指针
};
class IntelCPU :public CPU{
//Intel厂商的CPU继承公共父类CPU
public:
virtual void calculate(){
cout << "Intel的CPU开始计算了!" << endl;
}
};
class IntelVideoCard :public VideoCard{
//Intel厂商的VideoCard继承公共父类VideoCard
public:
virtual void display(){
cout << "Intel的显卡开始显示了!" << endl;
}
};
class IntelMemory :public Memory{
//Intel厂商的Memory继承公共父类Memory
public:
virtual void storage(){
cout << "Intel的内存条开始存储了!" << endl;
}
};
class LenovoCPU :public CPU{
public:
virtual void calculate(){
cout << "Lenovo的CPU开始计算了!" << endl;
}
};
class LenovoVideoCard :public VideoCard{
public:
virtual void display(){
cout << "Lenovo的显卡开始显示了!" << endl;
}
};
class LenovoMemory :public Memory{
public:
virtual void storage(){
cout << "Lenovo的内存条开始存储了!" << endl;
}
};
void test(){
CPU* intelCpu = new IntelCPU; //父类指针指向子类实例化对象
VideoCard* intelCard = new IntelVideoCard;
Memory* intelMem = new IntelMemory; //intelMem是局部变量
cout << "第一台电脑开始工作:" << endl;
Computer* computer1 = new Computer(intelCpu, intelCard, intelMem);//父类指针指向子类实例化对象,传入变量
computer1->work();
delete computer1;
cout << "-----------------------" << endl;
cout << "第二台电脑开始工作:" << endl;
Computer* computer2 = new Computer(new LenovoCPU, new LenovoVideoCard, new LenovoMemory);;
computer2->work();
delete computer2;
cout << "-----------------------" << endl;
cout << "第三台电脑开始工作:" << endl;
Computer* computer3 = new Computer(new LenovoCPU, new IntelVideoCard, new LenovoMemory);;
computer3->work();
delete computer3;
}
int main() {
test();
system("pause");
return 0;class Computer{
//计算机类
public:
Computer(CPU* cpu, VideoCard* vc, Memory* mem){
//抽象类不能实体化对象,只能用指针了
m_cpu = cpu;
m_vc = vc;
m_mem = mem;
}
}
运行结果:
注意多看多体会
class Computer{
//计算机类
public:
Computer(CPU* cpu, VideoCard* vc, Memory* mem){
//抽象类不能实体化对象,只能用指针了
m_cpu = cpu;
m_vc = vc;
m_mem = mem;
}
void work(){
m_cpu->calculate(); //让零件工作起来,调用接口
m_vc->display();
m_mem->storage();
}
private:
CPU* m_cpu; //CPU的零件指针
VideoCard* m_vc; //显卡零件指针
Memory* m_mem; //内存条零件指针
}