跳转到主要内容
Game Engine Oct 19, 2022 1 tags

析构函数

析构函数

cover

类的析构函数

类的析构函数是类的一种特殊的成员函数,它会在每次删除所创建的对象时执行。

析构函数的名称与类的名称是完全相同的,只是在前面加了个波浪号(~)作为前缀,它不会返回任何值,也不能带有任何参数。析构函数有助于在跳出程序(比如关闭文件、释放内存等)前释放资源。

下面的实例有助于更好地理解析构函数的概念

#include <iostream>
 
using namespace std;
 
class Line
{
   public:
      void setLength( double len );
      double getLength( void );
      Line();   // 这是构造函数声明
      ~Line();  // 这是析构函数声明
 
   private:
      double length;
};
 
// 成员函数定义,包括构造函数
Line::Line(void)
{
    cout << "Object is being created" << endl;
}
Line::~Line(void)
{
    cout << "Object is being deleted" << endl;
}
 
void Line::setLength( double len )
{
    length = len;
}
 
double Line::getLength( void )
{
    return length;
}
// 程序的主函数
int main( )
{
   Line line;
 
   // 设置长度
   line.setLength(6.0); 
   cout << "Length of line : " << line.getLength() <<endl;
 
   return 0;
}

当上面的代码被编译和执行时,它会产生下列结果:

Object is being created
Length of line : 6
Object is being deleted

析构函数与Static

#include<iostream>
#include<string>
using namespace std;

class Item
{
public:
	Item();
	~Item();

private:

};

Item::Item()
{
	cout << "An item has been created!\n";
}

Item::~Item()
{
	cout << "An item has been destroyde!\n";
}

int main() {

	Item item;

	system("pause");
}

当上面的代码被编译和执行时,它会产生下列结果:

An item has been created!

我们可以发现,此时析构函数并没有被执行,这是因为item被声明在main的作用域中,并且作用域结尾有*system(“pause”);*原本应该在这之后执行的析构函数被系统暂停掉了,所以并未执行。

因为析构函数的将会在调用构造函数的作用域结束时自动执行这一特性,我们只需把main改成

int main() {
	{
		Item item;
	}
	system("pause");
}

当上面的代码被编译和执行时,它会产生下列结果:

An item has been created!
An item has been destroyde!

配合Static静态变量关键词的话又可绕过该作用域

Related Articles

继续阅读