• 虚析构和纯虚析构


    虚析构

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

    结果:

  • 相关阅读:
    mysql对库,表,数据类型的操作以及完整性约束
    mysql数据库初步了解
    响应式及Bootstrap
    事件流丶事件对象
    JQuery初识(三 )
    JQuery初识(二)
    JQuery初识
    sencha touch tpl 实现按钮功能
    sencha touch 分享到微博扩展
    sencha touch 隐藏滚动条样式的几种方式
  • 原文地址:https://www.cnblogs.com/yifengs/p/15179484.html
Copyright © 2020-2023  润新知