析构函数是类的一种特殊函数,只有在对象被销毁时才被调用,在析构函数内,可以对堆内存进行释放,如new(构造函数),delete(析构函数)。
构造函数可以有多个(重载),而析构函数只有一个(不能对析构函数进行重载)。
如果忘记实现析构函数,编译器会自动生成一个伪析构函数(空函数),从下面代码,可以看出析构函数的使用及调用顺序。
/*Human.h*/
#include <string>
class Human
{
private:
std::string* name;//为了演示析构函数的作用
/*public类外可访问*/
public:
void getPersonName();
Human(std::string input);
~Human();
};
#include <iostream>
#include <string>
#include "Human.h"
/*构造函数(创建对象时被调用)*/
Human::Human(std::string input)
{
std::cout << "1 call Human()" << std::endl;
name = new std::string(input); //在构造函数中用new在堆上创建变量,在析构函数中释放
}
/*析构函数(对象被销毁时被调用,类只有一个析构函数*/
Human::~Human()
{
delete name; //在析构函数里面释放
std::cout << "2 call ~Human()" << std::endl;
}
/*类方法的实现*/
void Human::getPersonName()
{
std::cout << "3 get name is " << *name << std::endl;
}
#include <iostream>
#include "Human.h"
int main()
{
Human man("ONE"); //跟int一样,使用数据类型Hunam实例化对象,类内的成员和方法,只有实例化对象后才能被使用
man.getPersonName();
return 0;
}
输出:
1 call Human()
3 get name is ONE
2 call ~Human()
来源:CSDN
作者:降魔者
链接:https://blog.csdn.net/dddd0216/article/details/79730662