析构函数
来源:互联网 发布:java第三方支付 编辑:程序博客网 时间:2024/06/06 10:43
1. 析构函数
1) 函数名和类名相似(前面多了一个字符“~”)
2) 没有返回类型
3) 没有参数
4) 析构函数不能被重载
5) 如果没有定义析构函数,编译器会自动生成一个默认析构函数,其式如下:
类名::~默认析构名()
{
}
6) 默认析构函数是一个空函数
示例:
Test.h: #ifndef_TEST_H_ #define_TEST_H_ classTest { public: Test(int x,int y,int z); ~Test(); private: int x_; int y_; int z_; }; #endif Test.cpp: #include"Test.h" #include<iostream> usingnamespace std;Test::Test() { cout << "default initTest!" << x_ << endl; } Test::Test(intx, int y, int z) { x_ = x; y_ = y; z_ = z; cout << "init Test!"<< x_ << endl; } Test::~Test() { cout << "destory Test!"<< x_ << endl; } main.c #include<iostream> #include"Test.h" usingnamespace std; intmain() { Test t2();Testt1(1,2,3); Test t(4,5,6); Test *p = new Test(7,8,9); delete p; return 0; }在局部对象时,构造函数调用顺序与析构函数正好相反。
3.析构函数显式调用
1) 析构函数与数组
2) 析构函数与delete运算符
析构函数在变量释放时,才调用,所以只有delete之后,才会调用析构函数
代码示例:
Test.h: #ifndef_TEST_H_ #define_TEST_H_ classTest { public: Test(int x,int y,int z); Test(); ~Test(); private: int x_; int y_; int z_; }; #endif Test.cpp: #include"Test.h" #include<iostream> usingnamespace std; Test::Test() { cout << "default init Test!"<< endl; } Test::Test(intx, int y, int z) { x_ = x; y_ = y; z_ = z; cout << "init Test!"<< x_ << endl; } Test::~Test() { cout << "destory Test!"<< x_ << endl; } main.c #include<iostream> #include"Test.h" usingnamespace std; intmain() { Test *p = new Test[3]; delete[] p; return 0; }
3) 析构函数显示调用
0 0
- 函数 - 构造函数 - 析构函数
- 构造函数、析构函数、虚函数
- 虚函数/构造函数/析构函数
- 构造函数&析构函数&虚函数
- 构造函数,析构函数
- 构造函数,析构函数
- 构造函数+析构函数
- 构造函数/析构函数
- 析构函数 虚函数
- 析构函数 虚函数
- 构造函数 & 析构函数
- 构造函数 析构函数
- 析构函数,构造函数
- 构造函数、析构函数
- 构造函数,析构函数
- 构造函数,析构函数
- 构造函数,析构函数
- 虚函数 析构函数
- MySQL事务隔离级别详解
- MongoDB学习笔记—Linux下搭建MongoDB环境
- 并查集
- 邻接矩阵
- 三星掌门人李在镕首轮审判将于3月9日举行
- 析构函数
- 数据结构实验之链表五:单链表的拆分
- android-service
- 腾讯云服务器--django安装及基本配置
- 5-20 查找整数 (10分)
- python中矩阵相加函数sum()
- 联想十六亿再卖楼 经验来看:卖楼确实能提亮财报
- CentOS 7 防火墙 firewall-cmd
- win7系统注意