析构函数:
一、作用:通常用于撤销对象的一些清理任务,如释放分配给对象的内存空间 等。
二、性质:(除了具有一般成员函数的特征外)
第一,析构函数与构造函数和类的名字相同,但它前面必须加一个波浪号~。
第二,析构函数没有参数,也没有返回值,并且不能重载。所以在一个类中只能有一个析构函数。
第三,当撤销对象时,编译系统会自动地调用析构函数。
示例:
class Stu { private: char name[N],stu_no[N]; float score; public: Stu(char name1[],char stu_no1[],float score1); ~Stu(); void modify(float score1); void show(); }; Stu::Stu(char name1[],char stu_no1[],float score1)//构造函数 { strcpy(name,name1); strcpy(stu_no,stu_no1); score=score1; } Stu::~Stu()//析构函数 { cout<<"d........."<<endl; }
由于该类比较简单,对象在撤销时不要需要什么特殊的清理工作,因此我们让它输出一个d........来体现它的作用。
Ps:
第一,如果一个对象被定义在一个函数体内(包括主函数),则当这个函数结束时,该对象的析构函数被自动调用。
示例:
#include<iostream> #include<cstring> using namespace std; const int N=10; class Stu { private: char name[N],stu_no[N]; float score; public: Stu(char name1[],char stu_no1[],float score1); ~Stu(); void modify(float score1); void show(); }; Stu::Stu(char name1[],char stu_no1[],float score1) { strcpy(name,name1); strcpy(stu_no,stu_no1); score=score1; } Stu::~Stu() { cout<<"d........."<<endl; } void Stu::modify(float score1) { score=score1; } void Stu::show() { cout<<name<<' '<<stu_no<<' '<<score<<endl; } int main() { Stu a("Mr.zhang","1206655023",100); a.show(); a.modify(99); a.show(); return 0; }
第二,若一个对象是使用new运算符动态创建的,在程序delete运算符释放它时,delete会自动调用析构函数(通常,在程序中不显示撤销该对象,系统的不会自动调用析构函数去撤销的)。
示例:
#include<iostream> #include<cstring> using namespace std; const int N=10; class Stu { private: char *name,*stu_no; float score; public: Stu(char *name1,char *stu_no1,float score1); ~Stu(); void modify(float score1); void show(); }; Stu::Stu(char *name1,char *stu_no1,float score1) { name=new char[N]; strcpy(name,name1); stu_no=new char[N]; strcpy(stu_no,stu_no1); score=score1; } Stu::~Stu() { delete []name;//释放动态分配的数组存储区. delete []stu_no; cout<<"d........."<<endl; } void Stu::modify(float score1) { score=score1; } void Stu::show() { cout<<name<<' '<<stu_no<<' '<<score<<endl; } int main() { Stu a("Mr.zhang","1206655023",100); a.show(); a.modify(99); a.show(); return 0; }
说明:在构造函数中用运算符new为字符串分配存储空间,最后在析构函数中用运算符delete释放已分配的存储空间。这是构造函数和析构函数常见的用法。
在简单的学习了构造函数和析构函数后,个人感觉,构造函数比起析构函数要重要多了。但是,这中感觉奇怪多了,就有中虎头蛇尾的感觉。