为什么用虚析构函数C++

本文通过一个C++示例程序展示了虚析构函数的重要性,特别是当基类指针指向派生类对象并被删除时,确保正确调用派生类的析构函数,避免资源泄露。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

//#include "stdafx.h"
#include <iostream>

using namespace std;

/*如果delete一个基类的指针时, 如果它指向的是一个子类的对象,
那么析构函数不为虚就会导致无法调用子类析构函数,从而导致资源泄露*/

class Animal
{
public:
    Animal(string _name) :name(_name) {}
    virtual void cry() const = 0;
    virtual ~Animal() { cout << "~Animal" << endl; }
protected:
    string name;
};

class Mouse : public Animal
{
public:
    Mouse(string _name, bool _sex) : Animal(_name), sex(_sex) {}
    virtual void cry() const
    {
        cout << "I'm " << name << ". I'm " << (sex ? "boy" : "girl") << ".吱吱吱" << endl;
    }
    virtual ~Mouse() { cout << "~Mouse" << endl; }
protected:
    bool sex;
};

class Cat : public Animal
{
public:
    Cat(string _name, bool _sex) : Animal(_name), sex(_sex) {}
    virtual void cry() const
    {
        cout << "I'm " << name << ". I'm " << (sex ? "boy" : "girl") << ".喵喵喵" << endl;
    }
    virtual ~Cat() { cout << "~Cat" << endl; }
protected:
    bool sex;
};

class Dog : public Animal
{
public:
    Dog(string _name, bool _sex) : Animal(_name), sex(_sex) {}
    virtual void cry() const
    {
        cout << "I'm " << name << ". I'm " << (sex ? "boy" : "girl") << ".汪汪汪" << endl;
    }
    virtual ~Dog() { cout << "~Dog" << endl; }
protected:
    bool sex;
};

void Cry(Animal *Ap)
{
    Ap->cry();
}

void Cry2(Animal &Ar)
{
    Ar.cry();
}

void Pause()
{
    Animal *Ap = NULL;
    Ap = new Mouse("Tom", 1);
    Cry(Ap);
    Cry2(*Ap);
    delete Ap;

    Ap = new Cat("Fairy", 0);
    Cry(Ap);
    delete Ap;

    Ap = new Dog("Jack", 1);
    Cry(Ap);
    delete Ap;
}

int main()
{
    Pause();

    system("pause");
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值