AllBull 2022-01-19 00:49 采纳率: 40%
浏览 18

虚函数的析构问题,虚析构

下面这段代码中在堆区 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;
}
  • 写回答

1条回答 默认 最新

  • _GX_ 2022-01-19 04:28
    关注

    CPU, GPUMM基类里需要定义虚析构函数

    评论

报告相同问题?

问题事件

  • 创建了问题 1月19日

悬赏问题

  • ¥15 关于#单片机#的问题:以ATMEGA128或相近型号单片机为控制器设计直流电机调速的闭环控制系统(相关搜索:设计报告|软件设计|流程图)
  • ¥15 打开软件提示错误:failed to get wglChoosePixelFormatARB
  • ¥30 电脑误删了手机的照片怎么恢复?
  • ¥15 (标签-python|关键词-char)
  • ¥15 python+selenium,在新增时弹出了一个输入框
  • ¥15 苹果验机结果的api接口哪里有??单次调用1毛钱及以下。
  • ¥20 学生成绩管理系统设计
  • ¥15 来一个cc穿盾脚本开发者
  • ¥15 CST2023安装报错
  • ¥15 使用diffusionbert生成文字 结果是PAD和UNK怎么办