析构函数

康康代码:

#include <iostream>
#include <cstring>


using namespace std;

class Test
{
private:
    int a;
    char *str;

public:
    Test(int b,char *s)
    {
        a=b;
        str=new char[strlen(s)+1];
        strcpy(str,s);
    }
    void setA(int b) {a=b;}
    void setStr(char *s) {strcpy(str,s);}
    void show() {cout<<a<<","<<str<<endl;}

    Test(const Test&C)
    {
        a=C.a;
        str=new char[strlen(C.str)+1];
        strcpy(str,C.str);
    }
    ~Test()
    {
        delete str;
    cout<<"xigouhanshu"<<endl;
    }
};

int main()
{
    Test xx(100,"hello");
    Test yy(xx);
    xx.show();  yy.show();
    xx.setA(80);  xx.setStr("abc");
    xx.show();     yy.show();
}

运行结果为:
100,hello
100,hello
80,abc
100,hello
xigouhanshu
xigouhanshu

函数执行顺序:
在这里插入图片描述

再看一个代码:

#include <iostream>
#include <cstring>


using namespace std;

class Test
{
private:
    int a;
    char *str;

public:
    Test(int b,char *s)
    {
        a=b;
        str=new char[strlen(s)+1];
        strcpy(str,s);
    }
    void setA(int b) {a=b;}
    void setStr(char *s) {strcpy(str,s);}
    int getA( )    {return a; }
    void show() {cout<<a<<","<<str<<endl;}

    Test(const Test&C)
    {
        a=C.a;
        str=new char[strlen(C.str)+1];
        strcpy(str,C.str);
    }
    ~Test()
    {
        delete str;
    cout<<"xigouhanshu"<<endl;
    }

};
Test  a(100,"hello");
void f(char xx[])
{
    cout<<"function f:"<<endl;
Test x(90,xx);
static Test y(0,"static");
x.show( ); y.show( );
y.setA(y.getA( )+10);
}

int main()
{
    Test b(a);
    a.show();  b.show();
    b.setA(80);  b.setStr("abc");
    a.show();     b.show();
    f("111");f("222");f("333");
}

运行结果为:

100,hello
100,hello
100,hello
80,abc
function f:
90,111
0,static
xigouhanshu
function f:
90,222
10,static
xigouhanshu
function f:
90,333
20,static
xigouhanshu
xigouhanshu
xigouhanshu
xigouhanshu

静态(static)局部变量在调用结束时并不释放,在main函数结束后才会调用析构函数

最后三个输出的xigouhanshu一个是静态对象的析构函数一个是Test a一个是Test b的析构函数

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值