This article address: http://www.cnblogs.com/archimedes/p/cpp-destructor.html, reprint please indicate source address
Function: Perform cleanup work before destroying objects
Format:
[Class Name::]~ class name ()
{
....
}
classstudent{ Public: Student (...); ~student ();//~ Symbol voidDisplay ()Const;Private: intM_inum; stringM_strname; CharM_csex; }; Student::~Student () {cout<<"destructor"<<Endl;} ...
Attention:
The function name is the same as the class name, and the number of functions is pre-added ~
No parameters, cannot be overloaded
Do not specify a return value
often defined as public
Automatic invocation at end of object lifetime
Thinking:
Usually there is no need to define destructors, when do you have to define destructors?
In general, when a class contains a pointer member, and the pointer points to memory in a heap in the constructor, you must define the dynamic space that the destructor should release for that pointer request
#include <iostream>using namespacestd;classstring{ Public: String (); voidDisplay ()Const;Private: Char * m_pstr;}; String::string () {m_pstr= New char[ +]; strcpy (M_pstr,"Hello");}voidString::d isplay ()Const{cout<<m_pstr<<Endl;}/*string::~string () {//system-generated}*/intMain () {String str; Str.display (); System ("Pause"); return 0;}
Look at the following code, using the destructor of your own definition--example code 1:
#include <iostream>using namespacestd;classstring{ Public: String (); ~String (); voidDisplay ()Const;Private: Char*M_pstr;}; String::string () {m_pstr=New Char[ +]; strcpy (M_pstr,"Hello");} String::~String () {delete []m_pstr;}voidString::d isplay ()Const{cout<<m_pstr<<Endl;}intMain () {String str; Str.display (); System ("Pause"); return 0;}
Example code 2:
#include <iostream>using namespacestd;classstring{ Public: String (Char*ap =" China"); ~String (); voidDisplay ()Const;Private: Char*M_pstr;}; String::string (Char*AP) {M_pstr=New Char[Strlen (AP) +1]; strcpy (M_PSTR, AP);} String::~String () {delete []m_pstr;}voidString::d isplay ()Const{cout<<m_pstr<<Endl;}intMain () {String str1 ("USA"); Str1.display (); String str2; Str2.display (); System ("Pause"); return 0;}
If you want to define destructors, you often need to define overloaded functions for copy constructors and assignment operators. For copy constructors, refer to the C + + copy constructor
C + + destructor