析構(gòu)函數(shù)是在對象銷毀時被調(diào)用的函數(shù),當實例化一個對象時占用的資源需要程序員手動回收時,一般用來釋放資源。析構(gòu)函數(shù)的定義格式:~類名(){}。析構(gòu)函數(shù)沒有任何參數(shù)。
//文件名為Student.h#include <iostream>#include <string>using namespace std;class Student {public: Student(); Student(const Student &stu); ~Student();//析構(gòu)函數(shù),對象被銷毀時會自動調(diào)用PRivate: char *m_pName;};#include "Student.h"Student::Student() { m_pName = new char[20];//從堆中申請的內(nèi)存,需要手動回收}Student::Student(const Student &stu) { cout << "調(diào)用拷貝構(gòu)造函數(shù)" << endl;}Student::~Student() { delete m_pName;//釋放對象占用的內(nèi)存 m_pName = NULL; cout << "我要死啦!" << endl;//函數(shù)體}/*作為函數(shù)參數(shù)傳遞過來的對象實際上生成了一個對象的副本(利用拷貝構(gòu)造函數(shù)),當函數(shù)執(zhí)行完畢后,這個對象的副本會被銷毀,這時也會調(diào)用析構(gòu)函數(shù)*/void test(Student stu) {}int main() { Student stu1; Student stu2 = stu1; Student stu3(stu1); test(stu1); system("pause"); return 0; //這里并沒有調(diào)用析構(gòu)函數(shù),但是程序執(zhí)行完畢時系統(tǒng)會自動調(diào)用}新聞熱點
疑難解答