析构函数
-
作用:
对象销毁前,做清理工作。 -
具体的清理工作,一般和构造函数对应
比如:如果在构造函数中,使用new分配了内存,就需在析构函数中用delete释放。 -
如果构造函数中没有申请资源(主要是内存资源),
那么很少使用析构函数。 -
函数名:
~类型
没有返回值,没有参数,最多只能有一个析构函数 -
访问权限:
一般都使用public -
使用方法:
不能主动调用。
对象销毁时,自动调用。
如果不定义,编译器会自动生成一个析构函数(什么也不做)
定义:
~Human();
实现:
Human::~Human(){
//delete ....
}
调用:
对象结束时自动调用
Human.h
#pragma once
#include <string>
#include <iostream>
#include <Windows.h>
using namespace std;
class Human {
public:
Human();
//定义了析构函数
~Human();
Human(string name, int age, string sex);
string getName() const;
string getSex() const;
int getAge() const;
const char* getAddr()const;
void description() const;
private:
string name; //姓名
string sex; //性别
int age; //年龄
char* addr; //地址
};
Human.cpp
#include "Human.h"
#define ADDR_LEN 64
Human::Human() {
name = "无名";
sex = "未知";
age = 18;
const char* addr_s = "China";
addr = new char[ADDR_LEN];
strcpy_s(addr, ADDR_LEN, addr_s);
}
Human::Human(string name, int age, string sex) {
this->age = age;
this->name = name;
this->sex = sex;
const char* addr_s = "China";
addr = new char[ADDR_LEN];
strcpy_s(addr, ADDR_LEN, addr_s);
}
string Human::getName() const {
return name;
}
string Human::getSex() const {
return sex;
}
int Human::getAge() const {
return age;
}
const char* Human::getAddr() const{
return addr;
}
Human::~Human(){
if (addr) { //如果addr不为空
delete[] addr; //释放内存
*addr = NULL; //指向空
}
}
main.cpp
#include "Human.h"
using namespace std;
int main(void) {
Human zhangsan("张三", 18, "男");
zhangsan.description();
system("pause");
return 0;
}