• 虚析构和纯虚析构


    虚析构

    • 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;
    }

    结果:

  • 相关阅读:
    java多线程
    异常处理
    mabits
    梦想改造家之全世界最治愈的家浅析
    Activity
    java基础终稿
    Visual Studio Codes配置vs2017编译
    2017-2018-2 20179216 《网络攻防与实践》SM234算法
    2017-2018-2 20179216 《网络攻防与实践》 免杀技术
    2017-2018-2 20179216 《网络攻防与实践》 SQL注入攻击
  • 原文地址:https://www.cnblogs.com/yifengs/p/15179484.html
Copyright © 2020-2023  润新知