Dotcpp  >  编程教程  >  C++类和对象  >  C++中的析构函数(Destructor)

C++中的析构函数(Destructor)

点击打开在线编译器,边学边练

除了上一节讲到的类对象在创建时自动调用的构造函数,在对象销毁时也会自动调用一个函数,它也和类名同名,也没有返回值,名字前有一个波浪线~,用来区分构造函数,它的作用主要是用做对象释放后的清理善后工作。它就是析构函数


与构造函数相同的是,与类名相同,没有返回值,如果用户不定义,系统也会自动生成一个空的析构函数。而一旦用户定义,则对象在销毁时自动调用。


与构造函数不同的是,虽然他俩都为公开类型。构造可以重载,有多个兄弟,而析构却不能重载,但它可以是虚函数,一个类只能有一个析构函数。


下面,我们以Student类为例,继续添加析构函数,同时在构造函数和析构函数中都添加了输出当前类的信息,用来辨别哪一个类的创建和销毁,请大家仔细阅读代码:

#include<iostream>
#include<Cstring>
using namespace std;
class Student
{
    private:
    int num;//学号
    char name[100];//名字
    int score;//成绩
    public:
    Student(int n,char *str,int s);
    ~Student();
    int print();
    int Set(int n,char *str,int s);
};
Student::Student(int n,char *str,int s)
{
     num = n;
     strcpy(name,str);
     score = s;
     cout<<num<<" "<<name<<" "<<score<<" ";
     cout<<"Constructor"<<endl;
}
Student::~Student()
{
    cout<<num<<" "<<name<<" "<<score<<" ";
    cout<<"destructor"<<endl;
}
int Student::print()
{
    cout<<num<<" "<<name<<" "<<score<<endl;
    return 0;
}
int Student::Set(int n,char *str,int s)
{
     num = n;
     strcpy(name,str);
     score = s;
}
int main()
{
    Student A(100,"dot",11);
    Student B(101,"cpp",12);
    return 0;
}


请大家仔细理解上述代码中的构造函数和析构函数,并注意主函数中定义了两个对象A和B,并亲自上机测试,可以看到运行效果如下:

C++中的析构函数


可以看到对象A和B的构造函数的调用顺序以及析构函数的调用顺序,完全相反!原因在于A和B对象同属局部对象,也在栈区存储,也遵循“先进后出”的顺序!


请大家务必亲自上机测试验证结果!



知识点标签:类和对象


本文固定URL:https://www.dotcpp.com/course/67

C++教程
第一章 C++入门
第二章 C++表达式和控制语句
第三章 C++函数调用与重载、内联
第四章 C++类和对象
第五章 C++继承与派生
第六章 C++多态性
第七章 C++异常处理
第八章 C++文件操作
Dotcpp在线编译      (登录可减少运行等待时间)