本文地址:http://www.cnblogs.com/archimedes/p/cpp-destructor.html,轉載請注明源地址
功能:銷毀對象前執行清除工作
格式:
[類名::]~類名()
{
....
}
class Student
{public:
Student(...);
~Student();//~符號
void display()const;
private:
int m_iNum;
string m_strName;
char m_cSex;
};
Student::~Student()
{ cout<<"Destructor "<<endl;}
… …
注意:
函數名與類名相同,且函數名前加~
沒有參數、不能被重載
不指定返回值
常定義為public
對象生命期結束時自動調用
思考:
通常不需人為定義析構函數,什麼時候必須定義析構函數?
一般,當類中含有指針成員,並且在構造函數中用指針指向了一塊堆中的內存,則必須定義析構函數釋放該指針申請的動態空間
#include<iostream>
using namespace std;
class String
{
public:
String();
void display() const;
private:
char *m_pstr;
};
String::String()
{
m_pstr = new char[1000];
strcpy(m_pstr, "hello");
}
void String::display() const
{
cout<<m_pstr<<endl;
}
/*
String::~String()
{
//系統生成的
}
*/
int main()
{
String str;
str.display();
system("pause");
return 0;
}
看下面的代碼,使用自己定義的析構函數--示例代碼1:
#include<iostream>
using namespace std;
class String
{
public:
String();
~String();
void display() const;
private:
char *m_pstr;
};
String::String()
{
m_pstr = new char[1000];
strcpy(m_pstr, "hello");
}
String::~String()
{
delete []m_pstr;
}
void String::display() const
{
cout<<m_pstr<<endl;
}
int main()
{
String str;
str.display();
system("pause");
return 0;
}
示例代碼2:
#include<iostream>
using namespace std;
class String
{
public:
String(char *ap = "china");
~String();
void display() 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;
}
void String::display() const
{
cout<<m_pstr<<endl;
}
int main()
{
String str1("USA");
str1.display();
String str2;
str2.display();
system("pause");
return 0;
}
如果要定義析構函數,通常也需要定義拷貝構造函數和賦值運算符的重載函數。關於拷貝構造函數,可以參考《C++拷貝構造函數》