Destructor 2.characteristics: The name of destructor is the same as constructor except with a“~”before it;: Destructor has no parameters and no returning value,and can't be overload.So there is only a destructor within a class. 2017年4月26日12时 H0身 第9章关于类和对象的进一步讨 22 论 BACK NEXT
HOME2017年4月26日12时 15分 第9章 关于类和对象的进一步讨 论 22 • 2. characteristics: • The name of destructor is the same as constructor except with a “ ~ ” before it; • Destructor has no parameters and no returning value, and can’t be overload. So there is only a destructor within a class
9.2析构函数 析构函数(destructor)作用不是删除对象,而是在撤 销对象占用的内存之前完成一些清理工作,使这部 分内存可以被程序分配给新对象使用。 一个类只能有一个析构函数 析构函数不返回任何值,没有函数类型,也没有函 数参数。不能被重载。 它的名字是类名的前面加一个“ヘ”符号。如 Time() 如果用户没有定义析构函数,C++编译系统会自动生 成一个空的析构函数。 2017年4月26日12时 0吧分 第9章关于类和对象的进一步讨 论 BACK NEX
HOME2017年4月26日12时 15分 第9章 关于类和对象的进一步讨 论 23 析构函数(destructor) 作用不是删除对象,而是在撤 销对象占用的内存之前完成一些清理工作,使这部 分内存可以被程序分配给新对象使用。 一个类只能有一个析构函数 析构函数不返回任何值,没有函数类型,也没有函 数参数。不能被重载。 它的名字是类名的前面加一个“~”符号。如 ~Time( ) 如果用户没有定义析构函数,C++编译系统会自动生 成一个空的析构函数
当对象的生命期结束时,会自动执行析构函数。 ①自动局部对象在对象释放前自动执行析构函数。 ②static局部对象在main函数结束或调用exit函数结 束程序时,调用析构函数。 ③全局对象在程序的流程离开其作用域时(如main函 数结束或调用exit函数)时,调用该全局对象的析构 函数。 ④用new建立的动态对象,当用delete运算符释放该 对象时,调用该对象的析构函数。 2017年4月26日12时 第9章关于类和对象的进一步讨 HO 15分 论 BACK NEX
HOME2017年4月26日12时 15分 第9章 关于类和对象的进一步讨 论 24 当对象的生命期结束时,会自动执行析构函数。 ①自动局部对象在对象释放前自动执行析构函数。 ②static局部对象在main函数结束或调用exit函数结 束程序时,调用析构函数。 ③全局对象在程序的流程离开其作用域时(如main函 数结束或调用exit函数) 时,调用该全局对象的析构 函数。 ④用new建立的动态对象,当用delete运算符释放该 对象时,调用该对象的析构函数
例9.5包含构造函数和析构函数的程序 #include<string> #include<iostream> using namespace std; class Student /声明Student类 { public: Student(int n,string nam,char s /定义构造函数 { num=n; name=nam; sex=s; cout<<"Constructor called."<<endl; /输出提示信息 } StudentO /定义析构函数 cout<<"Destructor called."<<""<<num<<endl; }/输出提示信息 2017年4月26日12时 0务 第9章关于类和对象的进一步讨 论 BACK NEX
HOME2017年4月26日12时 15分 第9章 关于类和对象的进一步讨 论 25 #include<string> #include<iostream> using namespace std; class Student //声明Student类 { public: Student(int n,string nam,char s ) //定义构造函数 { num=n; name=nam; sex=s; cout<<"Constructor called."<<endl; //输出提示信息 }~Student() //定义析构函数 { cout<<"Destructor called."<<" " <<num<<endl; } //输出提示信息
void display( ∥定义成员函数 cout<<"num:"<<num<<endl; cout<<"name:"<<name<<endl; cout<<"sex:"<<sex<<endl<<endl; 3 private: int num; string name; char sex; 2017年4月26日12时 H0座5务 第9章关于类和对象的进一步讨 26 论 BACK NEXT
HOME2017年4月26日12时 15分 第9章 关于类和对象的进一步讨 论 26 void display() //定义成员函数 { cout<<"num: "<<num<<endl; cout<<"name: "<<name<<endl; cout<<"sex: "<<sex<<endl<<endl; } private: int num; string name; char sex; };