析构函数是在对象消亡时,自动被调用,用来释放对象占用的空间。
有四种方式会调用析构函数:
1.生命周期:对象生命周期结束,会调用析构函数。
2.delete:调用delete,会删除指针类对象。
3.包含关系:对象Dog是对象Person的成员,Person的析构函数被调用时,对象Dog的析构函数也被调用。
4.继承关系:当Person是Student的父类,调用Student的析构函数,会调用Person的析构函数。
第一种 生命周期结束
1#include <iostream> 2using namespace std; 3class Person{ 4public: 5 Person(){ 6 cout << "Person的构造函数" << endl; 7 } 8 ~Person() { 9 cout << "删除Person对象 " << endl; 10 } 11private: 12 int name; 13}; 14 15int main() { 16 Person person; 17 return 0; 18}
结果
1Person的构造函数 2删除Person对象
第二种 delete
对于new的对象,是指针,其分配空间是在堆上,故而需要用户删除申请空间,否则就是在程序结束时执行析构函数
1#include <iostream> 2using namespace std; 3class Person{ 4public: 5 Person(){ 6 cout << "Person的构造函数" << endl; 7 } 8 ~Person() { 9 cout << "删除Person对象 " << endl; 10 } 11private: 12 int name; 13}; 14 15int main() { 16 Person *person=new Person(); 17 delete person; 18 return 0; 19}
结果
1Person的构造函数 2删除Person对象
第三种 包含关系
1#include <iostream> 2using namespace std; 3class Dog{ 4public: 5 Dog(){ 6 cout << "Dog的构造函数" << endl; 7 } 8 ~Dog() { 9 cout << "删除Dog对象 " << endl; 10 } 11private: 12 int name; 13}; 14class Person{ 15public: 16 Person(){ 17 cout << "Person的构造函数" << endl; 18 } 19 ~Person() { 20 cout << "删除Person对象 " << endl; 21 } 22private: 23 int name; 24 Dog dog; 25}; 26 27 28int main() { 29 Person person; 30 return 0; 31}
结果
1Dog的构造函数 2Person的构造函数 3删除Person对象 4删除Dog对象
第四种 继承关系
1#include <iostream> 2using namespace std; 3 4class Person{ 5public: 6 Person(){ 7 cout << "Person的构造函数" << endl; 8 } 9 ~Person() { 10 cout << "删除Person对象 " << endl; 11 } 12private: 13 int name; 14 15}; 16class Student:public Person{ 17public: 18 Student(){ 19 cout << "Student的构造函数" << endl; 20 } 21 ~Student() { 22 cout << "删除Student对象 " << endl; 23 } 24private: 25 int name; 26 string no; 27}; 28 29int main() { 30 Student student; 31 return 0; 32}
结果
1Person的构造函数 2Student的构造函数 3删除Student对象 4删除Person对象
参考:https://blog.csdn.net/chen134225/article/details/81221382