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

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

相关推荐
你撅嘴真丑2 小时前
第九章-数字三角形
算法
uesowys2 小时前
Apache Spark算法开发指导-One-vs-Rest classifier
人工智能·算法·spark
ValhallaCoder2 小时前
hot100-二叉树I
数据结构·python·算法·二叉树
董董灿是个攻城狮2 小时前
AI 视觉连载1:像素
算法
智驱力人工智能3 小时前
小区高空抛物AI实时预警方案 筑牢社区头顶安全的实践 高空抛物检测 高空抛物监控安装教程 高空抛物误报率优化方案 高空抛物监控案例分享
人工智能·深度学习·opencv·算法·安全·yolo·边缘计算
yunteng5214 小时前
通用架构(同城双活)(单点接入)
架构·同城双活·单点接入
孞㐑¥4 小时前
算法——BFS
开发语言·c++·经验分享·笔记·算法
月挽清风4 小时前
代码随想录第十五天
数据结构·算法·leetcode
XX風4 小时前
8.1 PFH&&FPFH
图像处理·算法
麦聪聊数据4 小时前
Web 原生架构如何重塑企业级数据库协作流?
数据库·sql·低代码·架构