Title

c++学习笔记——析构函数

析构函数

析构函数存在的意义

  • 析构函数是对撤销对象占用的内存之前完成的一些清理工作,而不是所谓的删除对象(个人理解:这些清理工作相当于把某种联系给拔除了,从而方便内存的撤销)

其他

  • 类的设计者可以通过设计析构函数来完成自己在删除对象前想要看到的操作
  • 在没有定义析构函数的情况下,编译器会自动定义出析构函数
  • 由于析构函数没有参数,也没有返回值、函数类型,故无法被特殊识别,故不能被重载。

格式

~类名(){}

代码

#include<iostream>
#include<stdio.h>
using namespace std;
class Student
{
	public:
		Student(int n,string nam,char s)
		{
			num=n;
			name=nam;
			sex=s;
			cout<<"Construtor called."<<endl<<endl;
		}
		~Student() 
		{
			cout<<name<<"    Destructor called."<<endl;
		}
		
		void display()
		{
			cout<<"num : "<<num<<endl;
			cout<<"name : "<<name<<endl;
			cout<<"sex : "<<sex<<endl<<endl;
		}
	private:
		int num;
		string name;
		char sex;
};

int main()
{
	Student stud1(10010,"Juan_Wang",'f');
	stud1.display();
	
	Student stud2(10010,"Ke_hong",'f');
	stud2.display();
	
	return 0;
}

输出

Construtor called.

num : 10010
name : Juan_Wang
sex : f

Construtor called.

num : 10010
name : Ke_hong
sex : f

Ke_hong    Destructor called.
Juan_Wang    Destructor called.

代码小结

  • 由输出可知,函数构造和函数析构的关系相当于是一个进栈和出栈的操作,先进栈的后出栈,先构造的后析构
posted @ 2021-03-31 09:35  BeautifulWater  阅读(147)  评论(0编辑  收藏  举报