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