这期是细狗(划掉)析构函数

析构函数是与构造函数作用相反的函数,它的名字是在类名的前面加一个“~"。这个符号在C++中是位取反运算符。当对象的生命期结束时,会自动执行析构函数。

细狗函数不能被重载。

与构造函数类似,如果你不自己定义细狗函数,系统会帮你搞一个,但是不起任何作用。

can can 代码:

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

class Student
{
public:
	Student(int n, string nam, char s)            //定义有参数的构造函数
	{
		num = n;
		name = nam;
		sex = s;
		cout << "Constructor called." << endl;
	}
	~Student()                                   //定义析构函数
	{
		cout << "Destructor called." << endl;
	}
	void display()                               //定义成员函数
	{
		cout << "num: " << num << endl;
		cout << "name: " << name << endl;
		cout << "sex: " << sex << endl << endl;
	}
private:
	int num;
	string name;
	char sex;
};
int main()
{
	Student stud1(10010, "Wang_li", 'f');       //建立对象stud1
	stud1.display();
	Student stud2(10011, "Zhang_fan", 'm');     //建立对象stud2
	stud2.display();
	return 0;
}

运行结果:

Constructor called.  //执行stud1的构造函数
num: 10010           //执行stud1的display函数
name: Wang_li
sex: f

Constructor called. //执行stud2的构造函数
num: 10011          //执行stud2的display函数
name: Zhang_fan
sex: m

Destructor called.  //执行stud2的析构函数
Destructor called.  //执行stud1的析构函数

进一步解释

在使用构造函数和析构函数时,要特别注意对它们的调用时间和调用顺序。

实际上,在一般情况下,调用析构函数的次序正好与调用构造函数的次序相反:最先被调用的构造函数,其对应的(同一对象中的)析构函数最后被调用;最后被调用的构造函数,其对应的析构函数最先被调用。

先构造的后析构,后构造的先析构。

ps.对于静态局部对象需另行分析。

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值