析构函数作用
对象销毁前调用,和构函数相对应,一般用来清理对象构造函数申请的堆区空间。
析构函数特点
1、没有返回值,没有参数,最多只能有一个析构函数
2、函数名:~类名();
3、不能主动调用,对象销毁时自动调用
4、如果不定义析构函数,那么编译器会自己定一个析构函数(什么都不做)
程序
Student.h
#pragma once
#include<iostream>
using namespace std;
class Student {
public:
Student(); // 自定义默认构造函数
~Student(); // 析构函数
private:
int age;
char* addr;
char* name;
};
Student.cpp
#include "Student.h"
Student::Student() {
cout << __FUNCTION__ << endl;
this->age = 12;
this->addr = new char[20];
this->name = new char[20];
}
// 析构函数实现
Student::~Student() {
cout << __FUNCTION__ << endl;
if (addr) {
delete[] addr;
}
if (name) {
delete[] name;
}
}
main.cpp
#include "Student.h"
int main() {
Student s1;
return 0;
} // 程序结束销毁对象调用析构函数
结果:
Student::Student
Student::~Student