析构函数

本文详细介绍了析构函数的概念,包括其特点、如何定义以及在不同情况下的调用方式。通过具体的代码示例,展示了析构函数在数组和指针管理中的作用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值