C++中基类和派生类的析构函数

和构造函数类似,析构函数也不能被继承。与构造函数不同的是,在派生类的析构函数中不用显式地调用基类的析构函数,因为每个类只有一个析构函数,编译器知道如何选择,无需程序员干涉。

另外析构函数的执行顺序和构造函数的执行顺序也刚好相反:

  • 创建派生类对象时,构造函数的执行顺序和继承顺序相同,即先执行基类构造函数,再执行派生类构造函数。
  • 而销毁派生类对象时,析构函数的执行顺序和继承顺序相反,即先执行派生类析构函数,再执行基类析构函数。

具体看实例:

c 复制代码
    #include <iostream>
    using namespace std;
    class A{
    public:
        A(){cout<<"A constructor"<<endl;}
        ~A(){cout<<"A destructor"<<endl;}
    };
    class B: public A{
    public:
        B(){cout<<"B constructor"<<endl;}
        ~B(){cout<<"B destructor"<<endl;}
    };
    class C: public B{
    public:
        C(){cout<<"C constructor"<<endl;}
        ~C(){cout<<"C destructor"<<endl;}
    };
    int main(){
        C test;
        return 0;
    }

运行结果:

A constructor

B constructor

C constructor

C destructor

B destructor

A destructor

下面是一个多继承的实例:

c 复制代码
    #include <iostream>
    using namespace std;
    //基类
    class BaseA{
    public:
        BaseA(int a, int b);
        ~BaseA();
    protected:
        int m_a;
        int m_b;
    };
    BaseA::BaseA(int a, int b): m_a(a), m_b(b){
        cout<<"BaseA constructor"<<endl;
    }
    BaseA::~BaseA(){
        cout<<"BaseA destructor"<<endl;
    }
    //基类
    class BaseB{
    public:
        BaseB(int c, int d);
        ~BaseB();
    protected:
        int m_c;
        int m_d;
    };
    BaseB::BaseB(int c, int d): m_c(c), m_d(d){
        cout<<"BaseB constructor"<<endl;
    }
    BaseB::~BaseB(){
        cout<<"BaseB destructor"<<endl;
    }
    //派生类
    class Derived: public BaseA, public BaseB{
    public:
        Derived(int a, int b, int c, int d, int e);
        ~Derived();
    public:
        void show();
    private:
        int m_e;
    };
    Derived::Derived(int a, int b, int c, int d, int e): BaseA(a, b), BaseB(c, d), m_e(e){
        cout<<"Derived constructor"<<endl;
    }
    Derived::~Derived(){
        cout<<"Derived destructor"<<endl;
    }
    void Derived::show(){
        cout<<m_a<<", "<<m_b<<", "<<m_c<<", "<<m_d<<", "<<m_e<<endl;
    }
    int main(){
        Derived obj(1, 2, 3, 4, 5);
        obj.show();
        return 0;
    }

运行结果:

BaseA constructor

BaseB constructor

Derived constructor

1, 2, 3, 4, 5

Derived destructor

BaseB destructorBase

A destructor

从运行结果中还可以发现,多继承形式下析构函数的执行顺序和构造函数的执行顺序相反。

相关推荐
zh_xuan1 小时前
LeeCode 40.组合总和II
c语言·数据结构·算法
杨杨杨大侠1 小时前
Spring AI 系列(一):Spring AI 基础概念与架构入门
人工智能·spring·架构
前端小巷子1 小时前
Vue 3 运行机制
前端·vue.js·面试
潘锦1 小时前
Multi-Agent 系统的主从架构
架构·agent·ai编程
都叫我大帅哥2 小时前
动态规划:从懵逼到装逼,一篇让你彻底搞懂DP的终极指南
java·算法
艾莉丝努力练剑3 小时前
《递归与迭代:从斐波那契到汉诺塔的算法精髓》
c语言·学习·算法
超级皮皮8 小时前
力扣热题之stack
算法·leetcode·职场和发展
weixin_470740368 小时前
某算法的python执行汇编
汇编·python·算法
再学一点就睡9 小时前
实现大文件上传全流程详解(补偿版本)
前端·javascript·面试
是乐谷9 小时前
燧原科技招大模型训练算法工程师
科技·算法