zoukankan      html  css  js  c++  java
  • 虚析构和纯虚析构

    虚析构

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

    结果:

  • 相关阅读:
    Day9
    详解大端模式和小端模式
    gcc常用命令
    Vim自动补全插件----YouCompleteMe安装与配置
    Linux gdb调试器用法全面解析
    JavaSE——javac、javap、jad
    intellij IDEA 常用快捷键
    生成heap dump
    JVM——九大工具助你玩转Java性能优化
    JVM——参数设置、分析
  • 原文地址:https://www.cnblogs.com/yifengs/p/15179484.html
Copyright © 2011-2022 走看看