BZ易风

导航

 

虚析构

  • virtual ~类名() {}
  • 解决问题: 通过父类指针指向子类对象释放时候不干净导致的问题

纯虚析构函数

  • 写法  virtual ~类名() = 0
  • 类内声明  类外实现
  • 如果出现了纯虚析构函数,这个类也算抽象类,不可以实例化对象

不用虚析构的化,delete子类的时候,只会调用父类的析构

#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <string>
using namespace std;
class Animal
{
public:
    
    virtual void speak()
    {
        cout << "动物在叫" << endl;
    }
    ~Animal()
    {
        cout << "Animal析构函数" << endl;
    }
    
};
class Cat :public Animal
{
public:
    Cat(const char* name)
    {
        this->m_Name = (char*)malloc(strlen(name) + 1);
        strcpy(this->m_Name, name);
    }
    void speak()
    {
        cout << this->m_Name << "在叫:喵喵。。。" << endl;
    }
    ~Cat()
    {
        cout << "Cat析构函数" << endl;
        if (this->m_Name != NULL)
        {
            delete[] this->m_Name;
            this->m_Name = NULL;
        }
    }
    char* m_Name;
};

void test01()
{
    Animal* ani = new Cat("Tom");
    ani->speak();
    delete ani;
}
int main()
{
    test01();
    system("Pause");
    return 0;
}

结果:

所以需要虚析构或纯虚析构

#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <string>
using namespace std;
class Animal
{
public:
    
    virtual void speak()
    {
        cout << "动物在叫" << endl;
    }
    /*~Animal()
    {
        cout << "Animal析构函数" << endl;
    }*/
    virtual ~Animal() = 0;  //纯虚析构 类内声明
};
Animal::~Animal()           //类外实现
{
    cout << "Animal析构函数" << endl;
}
class Cat :public Animal
{
public:
    Cat(const char* name)
    {
        this->m_Name = (char*)malloc(strlen(name) + 1);
        strcpy(this->m_Name, name);
    }
    void speak()
    {
        cout << this->m_Name << "在叫:喵喵。。。" << endl;
    }
    ~Cat()
    {
        cout << "Cat析构函数" << endl;
        if (this->m_Name != NULL)
        {
            delete[] this->m_Name;
            this->m_Name = NULL;
        }
    }
    char* m_Name;
};

void test01()
{
    Animal* ani = new Cat("Tom");
    ani->speak();
    delete ani;
}
int main()
{
    test01();
    system("Pause");
    return 0;
}

结果:

 

posted on 2021-08-24 11:18  BZ易风  阅读(69)  评论(0编辑  收藏  举报