析构函数

1、析构函数

  • 成员函数的一种
  • 名字与类名相同
  • 没有参数与返回值
  • 一个类最多只能有一个析构函数
  • 对象消亡时自动调用
  • 定义类时如果没有写析构函数,则编译器生成缺省析构函数,缺省的析构函数不会进行用户申请的内存释放等清理工作
  • 定义了析构函数,则编译器不生成缺省析构函数

2、代码示例

#include<stdio.h>
#include<stdlib.h>
#include<iostream>
using namespace std;
class test
{
    private:
        int id;
    public:
        test(int i)
        {
            id=i;
            cout<<"constructor"<< id<<" called."<<endl;
        }
        ~test()
        {
            cout<<"destructor"<< id<<" called."<<endl;
        }
 } ;

 test a=3;
 int main()
 {
    static test b=4;
    test array[2]={1,2};
    return 0;
 }

实验结果:

constructor3 called.
constructor4 called.
constructor1 called.
constructor2 called.
destructor2 called.
destructor1 called.
destructor4 called.
destructor3 called.

从上面结果我们可以看出,析构函数调用顺序与构造函数调用顺序相反,即先被构造的对象,最后被析构。

 test a=3;
 int main()
 {
    static test b=4;
    {
     test b=5;
    }//局部作用域
    test array[2]={1,2};

    return 0;
 }

程序结果:

constructor3 called.
constructor4 called.
constructor5 called.
destructor5 called.
constructor1 called.
constructor2 called.
destructor2 called.
destructor1 called.
destructor4 called.
destructor3 called.
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值