C++--------析构函数

1.析构函数的目的是收回构造函数时申请的资源,垃圾回收

2.Destructorsare invoked when:  3种情况自动调用析构函数:

              we  leavethe scope of the object .//离开对象的作用域

              we wish to discard the object  //销毁对象

              we delete a pointer that points to an object.//删除一个指向对象的指针

3.析构函数是在构造函数之前加~.        比如: ~ Circle( )

4. Destructors:析构函数的四个特点

     1) Cannot return a value.//无返回值

     2)  Cannot take any parameters.//无参

     3) Cannot beoverloaded.    //唯一

     4)  Must be public //公有

5.当动态分配内存时,必须显式的销毁分配在堆上的空间,用delete回收指针指向的内存空间,避免发生内存泄露。

#include <iostream>
using namespace std;

class Test
{
public:
Test() { cout<< "hello world"<<endl;}	//函数定义写在类体内部。

//前面没有new,后面就不用delete
   ~Test() { cout<< "goodbye world"<<endl; }  
};


int main()
{
  Test t;
  return 0;
}

输出结果为:

hello world

goodbyeworld

5.当动态分配内存时,必须显式的销毁分配在堆上的空间,用delete回收指针指向的内存空间,避免发生内存泄露。

写个例子演示一下:

#include <iostream.h>

class Test
{
public:
Test()
{ 
   _pVar = new int[10];//手工分配内存;动态内存分配
   for( int i = 0; i<10; i++)
   {
      _pVar[i] = i;
   }
cout<< "hello world"<<endl;
}	

   ~Test()
 {
   if( _pVar != NULL )
{  
     //手工回收内存,
//以数组的形式删除指针,把new分配的10个整数空间全部收回。
//如果不加[]?内存泄露

delete [] _pVar;
     _pVar = NULL;//指针本身置0.

   }

cout<< "goodbye world"<<endl; 
}   
//在构造函数里new出的内存,一定要记得在析构函数里delete掉,
//然后指针= NULL。

void print()
{
   for( int i=0; i<10; i++)
       cout<<_pVar[i]<<endl;
}

private:
   int* _pVar;
};


void main()
{
  Test t;//t是局部变量,本身分配在栈上
         //t的成员_pVar是个指针,里面存储的是地址。
         //指针¬_pVar指向的new出来的堆空间,不是t的成员。
  t.print();
}
结果为:hello world
0
1
2
3
4
5
6
7
8
9
goodbye world

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值