C++基础知识 - 析构函数

析构函数

  • 作用:
    对象销毁前,做清理工作。

  • 具体的清理工作,一般和构造函数对应
    比如:如果在构造函数中,使用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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值