承三刀 2021-07-02 00:33 采纳率: 80%
浏览 19
已采纳

C++ 析构函数怎么写,代码有问题啊,求前辈指导

写了多基派生,然后要用到析构函数,发现自己写的析构函数有问题,一个自学的小菜鸟求前辈指导!!!

{
    private:
        string shape;    //形状
        int area;        //面积
    public:
        Fabric();
        Fabric(string shape,int area);
        void ventilation();    //透气
        ~Fabric();
        void show();
};

class Salve
{
    private:    
        string name;    
        int weight;        //重量
    public:
        Salve();
        Salve(string name,int weight);
        void effect();    //疗效
        ~Salve();
        void output();
};

class Plaster:public Fabric,public Salve
{
    private:    
        string color;    //颜色
        double primage;    //含水量
    public:
        Plaster();
        Plaster(string name,string shape,string color,double primage,int area,int weight);
        void usage();    //公用
        ~Plaster();
        void display();
};

Fabric::Fabric()
{}

Fabric::Fabric(string shape,int area)
{
    this->shape = shape;
    this->area = area;
}

void Fabric::ventilation()    //透气
{
    cout << "透气性是真的好!" << endl;
}

Fabric::~Fabric()    //析构函数
{
/*    if(shape != NULL)
    {
        delete []shape;
        shape = NULL;
    }

    if(area != NULL)
    {
        delete []area;
        area = NULL;
    }*/
}

void Fabric::show()
{
    cout << "shape:" << shape << endl;
    cout << "area:" << area << endl;
}

  • 写回答

2条回答 默认 最新

  • qfl_sdu 2021-07-02 00:50
    关注

    如果成员变量中有指针,并且在构造函数或者成员函数中对成员变量赋值(new或者malloc申请空间赋值),那么就需要在析构函数中释放申请的内存,如有没有指针,析构函数可以不用处理。

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效