C++类的析构函数

析构函数

~Test()

一,关于析构函数

特征:

  1. 函数名由~<类名>组成,无参数且无返回值
  2. 一个类只有一个析构函数,且无显示的定义,系统会生成一个缺省的析构函数(合成析构函数)
  3. 析构函数不能重载,其与构造函数一定是成对出现

作用:

构造函数相反,用于释放对象资源,并销毁非static成员。

程序示例:

 1 class Time
 2 {
 3 public:
 4     Time(int h)
 5     {
 6         cout << "I'm constructor" << endl;
 7     }
 8     ~Time()
 9     {
10         cout << "I'm destructor" << endl;
11     }
12 
13 private:
14     int m_hour;
15 };
16 
17 Time t(10);
18 system("pause");

 二,析构使用误区

 1 class Date
 2 {
 3 public:
 4     Date(int year=1990,int month=1,int day=1)
 5         : _year(year),_month(month),  _day(day)
 6     {
 7         p = new int;
 8         cout << "I'm constructor " << p << endl;
 9     }
10     ~Date()
11     {
12         cout << "I'm destructor " << p << endl;
13         delete p;
14     }
15 
16 private:
17     int _year=1990;
18     int _month;
19     int _day;
20     int *p;
21 };
22 
23 Date d1;
24 Date d2(d1);
25 system("pause");
26 
27 //结果
28 I'm constructor 034D19A0
29 Press any key to continue . . .
30 I'm destructor 034D19A0  //销毁
31 I'm destructor 034D19A0  //第二次销毁

<文档结束符>

猜你喜欢

转载自www.cnblogs.com/yechaoy/p/10710665.html