C++面向对象--第十三章虚析构、纯虚析构

引入

问题:为什么只能释放父类的析构

#include<iostream>

using namespace std;



class Animal

{

public:

    virtual void sleep(){

        cout<<"动物在睡觉"<<endl;

    }

    Animal() {

        cout<<"animal构造"<<endl;

    }

    ~Animal(){

        cout<<"animal析构"<<endl;

    }

};



class Cat:public Animal

{

public:

    virtual void sleep(){

        cout<<"动物在睡觉"<<endl;

    }

    Cat() {

        cout<<"Cat构造"<<endl;

    }

    ~Cat(){

        cout<<"Cat析构"<<endl;

    }

};



int main()

{

    Animal *p=new Cat;

    p->sleep();

    delete p;

    return 0;

}

原因:p指向的类型为Animal在没有涉及虚析构的时候只能调用父类的析构函数

解决:虚析构(虚函数)

虚析构

虚析构:在析构函数前加virtual修饰

作用

 虚析构作用:通过基类指针、引用释放子类的所有空间

#include<iostream>

using namespace std;



class Animal

{

public:

    virtual void sleep(){

        cout<<"动物在睡觉"<<endl;

    }

    Animal() {

        cout<<"animal构造"<<endl;

    }

    virtual ~Animal(){

        cout<<"animal析构"<<endl;

    }

};



class Cat:public Animal

{

public:

    virtual void sleep(){

        cout<<"猫在睡觉"<<endl;

    }

    Cat() {

        cout<<"Cat构造"<<endl;

    }

    ~Cat(){

        cout<<"Cat析构"<<endl;

    }

};



int main()

{

    Animal *p=new Cat;

    p->sleep();

    delete p;

    return 0;

}

深入研究

        

        

图解

        

        子类析构调用完,系统会自动调用父类析构

纯虚析构函数

特点

是特殊的虚函数

与普通纯虚函数不同点:纯虚析构函数不仅需要=0,而且需要定义函数体

原因:通过基类指针释放子类对象时,先调用子类析构,再父类析构(如果父类的析构不实现,无法实现调用)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值