析构函数
自动调用-------跟 构造函数相近析构函数
特点1:对象消失的时候自动调用
特点2:函数名----类名 相同;前边加~
特点3:系统有默认的析构函数(但它什么都不干)-------当有成员变量是动态内存分配时,就必须重写析构函数
特点4:函数原型永远就1个
//代码:
//main.cpp
#include <iostream>
#include <iomanip>
#include <string.h>
#include <stdlib.h>
#include "Student.h"
using namespace std;
int main()
{
CStudent stu1(1001,"zhangsan");
//stu1.free_name(); //如果没有析构函数,我
们就必须自己定义1个函数,来释放name;并手动来执行。----用了析构只是方便了
return 0;
}
//Student.cpp中完善 析构函数
CStudent::~CStudent()
{
free(name);
cout<<"析构函数运行了"<<endl;
}
如果使用new来建立 对象,就必须使用delete来释放对象------此时析构函数才会被调用
如果使用new来建立 对象,就必须使用delete来释放对象------否则,析构函数不会被调