析构函数(destructor)也是一个特殊的成员函数,它的作用与构造函数相反,它的名字时类名的前面加一个“~”符号。在C++中“~”是位取反运算符,从这点也可以想到:析构函数是与构造函数作用相反的函数
当对象的生命期结束时,会自动执行析构函数。
#include<iostream>
#include<string>
using namespace std;
class Student
{
public:
Student(int n, string nam, char s) //定义有参数的构造函数
{
num = n;
sex = s;
name = nam;
cout << "Contructor called." << endl;
}
~Student()//定义析构函数
{
cout << "Destructor called." << num << endl;//输出指定的信息
}
void display()
{
cout << "num:" << num << endl;
cout << "name:" << name << endl;
cout << "sex:" << sex << endl;
}
private:
int num;
string name;
char sex;
};
int main(void)
{
Student stud1(10010, "Wang_li", 'f');
stud1.display();
Student stud2(10011, "Zhang_fan", 'm');
stud2.display();
return 0;
}