析構函數是在對象消亡時,自動被調用,用來釋放對象占用的空間。
有四種方式會調用析構函數:
1.生命周期:對象生命周期結束,會調用析構函數。
2.delete:調用delete,會刪除指針類對象。
3.包含關系:對象Dog是對象Person的成員,Person的析構函數被調用時,對象Dog的析構函數也被調用。
4.繼承關系:當Person是Student的父類,調用Student的析構函數,會調用Person的析構函數。
第一種 生命周期結束
#include <iostream> using namespace std; class Person{ public: Person(){ cout << "Person的構造函數" << endl; } ~Person() { cout << "刪除Person對象 " << endl; } private: int name; }; int main() { Person person; return 0; }
結果
Person的構造函數
刪除Person對象
第二種 delete
對於new的對象,是指針,其分配空間是在堆上,故而需要用戶刪除申請空間,否則就是在程序結束時執行析構函數
#include <iostream> using namespace std; class Person{ public: Person(){ cout << "Person的構造函數" << endl; } ~Person() { cout << "刪除Person對象 " << endl; } private: int name; }; int main() { Person *person=new Person(); delete person; return 0; }
結果
Person的構造函數
刪除Person對象
第三種 包含關系
#include <iostream> using namespace std; class Dog{ public: Dog(){ cout << "Dog的構造函數" << endl; } ~Dog() { cout << "刪除Dog對象 " << endl; } private: int name; }; class Person{ public: Person(){ cout << "Person的構造函數" << endl; } ~Person() { cout << "刪除Person對象 " << endl; } private: int name; Dog dog; }; int main() { Person person; return 0; }
結果
Dog的構造函數
Person的構造函數
刪除Person對象
刪除Dog對象
第四種 繼承關系
#include <iostream> using namespace std; class Person{ public: Person(){ cout << "Person的構造函數" << endl; } ~Person() { cout << "刪除Person對象 " << endl; } private: int name; }; class Student:public Person{ public: Student(){ cout << "Student的構造函數" << endl; } ~Student() { cout << "刪除Student對象 " << endl; } private: int name; string no; }; int main() { Student student; return 0; }
結果
Person的構造函數 Student的構造函數 刪除Student對象 刪除Person對象
參考:https://blog.csdn.net/chen134225/article/details/81221382