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) 析构函数显示调用