下面这段代码中在堆区 new了子类 ,用父类指针指向了子类,通过computer类的析构函数只会调用各零件的抽象类的析构,而父类指向的子类的析构函数调用不到。
求这个对这段代码中的析构函数是否需要在零件抽象类中写虚析构?来释放子类的堆区空间?
#include <iostream>
#include <string>
using namespace std;
//零件
class CPU {
public:
virtual void calculate() = 0;
};
class GPU {
public:
virtual void display() = 0;
};
class MM {
public:
virtual void storage() = 0;
};
//电脑
class Computer {
public:
Computer(CPU* cpu, GPU* gpu, MM* mm) {
this->cpu = cpu;
this->gpu = gpu;
this->mm = mm;
}
void work() {
cpu->calculate();
gpu->display();
mm->storage();
}
~Computer() {
if (cpu != NULL) delete cpu;
if (gpu != NULL) delete gpu;
if (mm != NULL) delete mm;
}
private:
CPU* cpu;
GPU* gpu;
MM* mm;
};
//厂商
class InterCPU :public CPU {
public:
void calculate() {
cout << "Inter CPU ..." << endl;
}
};
class InterGPU :public GPU {
public:
void display() {
cout << "Inter GPU ..." << endl;
}
};
class InterMM :public MM {
public:
void storage() {
cout << "Inter MM ..." << endl;
}
};
class LenovoCPU :public CPU {
public:
void calculate() {
cout << "Lenovo CPU ..." << endl;
}
};
class LenovoGPU :public GPU {
public:
void display() {
cout << "Lenovo GPU ..." << endl;
}
};
class LenMM :public MM {
public:
void storage() {
cout << "Lenovo MM ..." << endl;
}
};
void test401() {
//1
CPU* interCpu = new InterCPU();
GPU* interGpu = new InterGPU();
MM* interMM = new InterMM();
Computer* c1 = new Computer(interCpu,interGpu,interMM);
c1->work();
delete c1;
//2
CPU* LenovoCpu = new LenovoCPU();
GPU* LenovoGpu = new LenovoGPU();
MM* LenovoMM = new LenMM();
Computer* c2 = new Computer(LenovoCpu, LenovoGpu, LenovoMM);
c2->work();
delete c2;
//3
Computer* c3 = new Computer(new LenovoCPU, new LenovoGPU, new LenMM);
c3->work();
delete c3;
}
int main() {
test401();
return 0;
}