析构函数Destructor与构造函数是相反的,构造函数一般完成些初始化工作,哪么析构函数就是完成一些收尾工作。
析构函数是在C++对象销毁的时候自己掉用。哪什么时候对象会被销毁?两种情况:
1.当某个对象离开作用域时;? ?作用域不明白的请看这篇:C++支持哪些作用域
2.当调用delete删除某个对象时;
析构函数的定义:
析构函数以“~”引起,函数名与类名一样,不能有返回值,参数表必须为空。
下面写段代码来分析析构函数的调用。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
//梁笔记 //zouzhongliang.com #include <iostream> using namespace std; class A { private: int a; public: A(){ cout<<"调用无参构造函数"<<endl; } ~A(){ cout<<"调用析构函数"<<endl; } void print(){ cout<<a<<endl; cout<<"成员函数print"<<endl; } }; int main() { A a2; A* pa = new A(); delete pa; return 0; } |
输出:
1 2 3 4 |
调用无参构造函数 调用无参构造函数 调用析构函数 调用析构函数 |
A a2;调用析构函数是因为main函数结束,a2对象销毁,这种就是对象离开作用域时调用。
delete pa;调用析构函数,因为delete删除pa对象销毁。
注:1.对象离开作用域时,析构函数调用,大家可以利用这一点。可以反过来,通过析构函数的调用来理解对象的作用域。比如不知道这个对象作用域是到哪,可以在析构函数里面做下标记,写个程序运行下,看什么调用析构函数,就说明作用域到哪。
2.可以在析构函数里做一些对象运行时的记录,在调用析构函数时保存。编程经验
Appreciate it! Quite a lot of knowledge!
fluconazol
Amazing lots of fantastic tips! fluconazole 200 mg
You actually reported it perfectly! fda cbd hearing
You reported it perfectly! viagra online without a prescrition
You actually said it very well. viagra for sale uk
Truly all kinds of superb material. hemp oil vs cbd oil for pain
With thanks! I like it! modafinil dosage
Awesome data. Many thanks! viagra 100mg price walmart
Nicely expressed without a doubt. ! Tretinoin .1 Cheap
Point very well used.! canada pharmaceutical online ordering
Regards, Numerous facts!
mexican pharmacies shipping to usa
Valuable content. With thanks! advair hfa
Cheers, Helpful stuff. online pharmacies of canada
Beneficial postings. Appreciate it. zanaflex medication
Seriously tons of beneficial information. drugs online
Nicely put, Many thanks. generic viagra 100mg
Nicely put, Thanks a lot! cbd heroin addiction
Thank you! Very good information! highest rated canadian pharmacies
Thank you! Useful stuff! https://viagradocker.com/
Truly many of useful info! top rated canadian pharmacies online