C++学习总结14--析构函数

小记:静默如初,安之若素

析构函数(Destructor)

1. 语法

class 类名{
 ~类名(void){}
 //负责清理对象创建时的动态资源
};

1)函数名必须是”~类名“;
2)没有返回类型,也没有参数,也无法重载;

2. 当对象销毁时,该类的析构函数会自动的被执行
1)栈对象当离开其作用域时,其析构函数被作用域终止的右花括号”}“调用;
2)堆对象的析构函数被delete操作符调用。

  1 #include<iostream>
  2 using namespace std;
  3 
  4 class Integer
  5 {
  6 public:
  7   Integer(int data = 0)
  8     :m_data(new int(data))
  9     {
 10       //m_data = new int(data);
 11   }
 12   ~Integer(void)
 13   {
 14     cout<<"xigouhanshu"<<endl;
 15     delete m_data;
 16   }
 17   
 18   void print(void) const
 19   { 
 20     cout << *m_data << std::endl;
 21   }
 22 
 23 private:
 24   int *m_data;//指针一定要注意最后释放,否则造成内存泄露
 25 };
 26 
 27 int main(int argc, char *argv[])
 28 { 
 29   if(1)
 30   { 
 31     Integer i(100);//对象的创建是在调用构造函数完成创建时获取的,
 32                     //销毁时分为栈和堆两种
 33     i.print();
 34     cout << "test1" << endl;
 35     
 36     Integer *pi = new Integer(200);
 37     pi->print();
 38     delete pi;//-->调用析构函数
 39     cout << "test3" << endl;
 40   }//-->调用析构函数
 41   cout << "tes2" << endl;
 42   return 0;
 43 }
~      

3. 如果一个类没有显示定义析构函数,那么系统会为该类提供一个缺省的析构函数:
1)对于基本类型的成员变量,什么也不做;
2)对于类类型的成员变量(成员子对象),会自动调用相应类的析构函数;

  1 #include <iostream>
  2 using namespace std;
  3 
  4 class A
  5 {
  6 public:
  7   A(void)
  8   {
  9     cout <<"A::A()"<<endl;
 10   }
 11   ~A(void)
 12   {
 13     cout <<"~A::A() "<<endl;
 14   }
 15 };
 16 
 17 class B
 18 {
 19 public:
 28   A m_a;//类类型的成员变量
 29 };
 30 
 31 int main(int argc, char *argv[])
 32 { 
 33   B b;
 34   return 0;
 35 }
 运行结果:
 A::A()
 ~A::A()

4. 对象创建和销毁过程
1)创建
1.1)分配内存
1.2)构造成员子对象(按照声明顺序)
1.3)执行构造函数代码

2)销毁
2.1)执行析构函数代码
2.2)析构成员子对象(按声明逆序)
2.3)释放内存

  1 #include <iostream>
  2 using namespace std;
  3 
  4 class A
  5 {
  6 public:
  7   A(void)
  8   {
  9     cout <<"A::A()"<<endl;
 10   }
 11   ~A(void)
 12   {
 13     cout <<"~A::A() "<<endl;
 14   }
 15 };
 16 
 17 class B
 18 {
 19 public:
 20   B (void)
 21   {
 22     cout <<"B::B()"<<endl;
 23   } 
 24   ~B(void)
 25   {
 26     cout <<"~B::B()"<<endl;
 27   } 
 28   A m_a;//类类型的成员变量
 29 };
 30 
 31 int main(int argc, char *argv[])
 32 { 
 33   B b;
 34   return 0;
 35 }

运行结果:
A::A()
B::B()
~B::B()
~A::A()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值