1. 析构函数的概念
2. 析构函数的特性
3 代码测试
#include<iostream>
using std::cout;
using std::endl;
class Date {
public:
/* 构造函数 */
Date(int year = 1970, int month = 1, int day = 1) {
_year = year;
_month = month;
_day = day;
cout << "构造函数!" << endl;
}
/* 析构函数 */
~Date() {
cout << "析构函数!" << endl;
}
void Print() {
cout << _year << "-" << _month << "-" << _day << endl;
}
private:
int _year;
int _month;
int _day;
};
int main() {
{ /* d1 若出了 {} 生命周期就结束了! */
Date d1;
}
return 0;
}

4. 析构函数的使用情形
代码示例
#include<iostream>
using std::cout;
using std::endl;
typedef int DataType;
/* 定义一个栈的及其构造函数 */
class Stack {
public:
Stack(int capacity = 4) { // 结合参数缺省实现:只要实例化必定是可用的栈(空间为:4)
_capacity = capacity;
_array = (DataType*)malloc(sizeof(DataType) * capacity); // 申请存储空间
if (_array == nullptr) {
perror("malloc fail!\n");
return;
}
_size = 0;
}
/* 析构函数:释放在堆上申请的空间! */
~Stack(){
if(_array){
cout << "析构函数" << endl;
free(_array);
}
}
private:
DataType* _array; // 顺序存储方式
int _capacity; // 记录当前栈的最大存储量
int _size; // 记录当前栈中的元素个数
};
int main() {
{
Stack stk;
}
return 0;
}

5. 析构顺序问题 及 类类型成员与析构函数
6. 相关文章推荐