C++中的析构函数(Destructor)

除了上一节讲到的类对象在创建时自动调用的构造函数,在对象销毁时也会自动调用一个函数,它也和类名同名,也没有返回值,名字前有一个个波浪线~,用来区分构造函数,它的作用主要是用做对象释放后的清理善后工作。它,就是析构函数

与构造函数相同的是,与类名相同,没有返回值,如果用户不定义,系统也会自动生成一个空的析构函数。而一旦用户定义,则对象在销毁时自动调用。

与构造函数不同的是,虽然他俩都为公开类型。构造可以重载,有多个兄弟,而析构却不能重载,但它可以是虚函数,一个类只能有一个析构函数。银行从业报名条件

下面,我们以Student类为例,继续添加析构函数,同时在构造函数和析构函数中都添加了输出当前类的信息,用来辨别哪一个类的创建和销毁,请大家仔细阅读代码:

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

35

36

37

38

39

40

41

42

43

44

45

#include<iostream>

#include<Cstring>

using namespace std;

class Student

{

    private:

    int num;//学号

    char name[100];//名字

    int score;//成绩

    public:

    Student(int n,char *str,int s);

    ~Student();

    int print();

    int Set(int n,char *str,int s);

};

Student::Student(int n,char *str,int s)

{

     num = n;

     strcpy(name,str);

     score = s;

     cout<<num<<" "<<name<<" "<<score<<" ";

     cout<<"Constructor"<<endl;

}

Student::~Student()

{

    cout<<num<<" "<<name<<" "<<score<<" ";

    cout<<"destructor"<<endl;

}

int Student::print()

{

    cout<<num<<" "<<name<<" "<<score<<endl;

    return 0;

}

int Student::Set(int n,char *str,int s)

{

     num = n;

     strcpy(name,str);

     score = s;

}

int main()

{

    Student A(100,"dot",11);

    Student B(101,"cpp",12);

    return 0;

}

请大家仔细理解上述代码中的构造函数和析构函数,并注意主函数中定义了两个对象A和B,并亲自上机测试,可以看到运行效果如下:

 

ds.png

可以看到对象A和B的构造函数的调用顺序以及构造函数的调用顺序,完全相反!原因在于A和B对象同属局部对象,也在栈区存储,也遵循“先进后出”的顺序!

请大家务必亲自上机测试!验证结果!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值