子类的析构顺序

本文介绍了派生类析构函数的执行顺序及其在对象消亡前进行必要清理工作的功能。通过C++代码示例展示了析构函数如何按子类到基类的顺序依次调用,并释放内存。

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

派生类的析构函数的功能是在该对象消亡之前进行一些必要的清理工作,析构函数没有类型,也没有参数。
析构函数的执行顺序与构造函数相反,无需指明析构关系,因为析构函数只有一种,无重载,无默参

析构顺序:子类->成员->基类

#include "stdafx.h"
#include <iostream>
using namespace std;

class A
{
public:
	A()
	{
		cout << "A()" << endl;
	}
	~A()
	{
		cout << "~A()" << endl;
	}
};


class Base
{
public:
	Base()
	{
		cout << "Base()" << endl;
		p = new char[100];
	}
	~Base()
	{
		cout << "~Base()" << endl;
		delete p;
	}

private:
	char* p;
};


class Derive:public Base
{
public:
	Derive()
	{
		cout << "Derive()" << endl;
		q = new char[200];
	}
	~Derive()
	{
		cout << "~Derive()" << endl;
		delete q;
	}
private:
	A a;
	char* q;
};


int _tmain(int argc, _TCHAR* argv[])
{

	Derive d;
	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值