0
点赞
收藏
分享

微信扫一扫

【音视频】C++调用析构函数梳理


C++调用析构函数梳理

析构函数是在对象消亡时,自动被调用,用来释放对象占用的空间。

有四种方式会调用析构函数:

  • 生命周期:对象生命周期结束,会调用析构函数。
  • delete:调用delete,会删除指针类对象。
  • 包含关系:对象Dog是对象Person的成员,Person的析构函数被调用时,对象Dog的析构函数也被调用。
  • 继承关系:当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对象


举报

相关推荐

0 条评论