C++的继承中构造和析构函数的调用顺序

本文通过具体的C++代码示例,详细介绍了类的构造函数与析构函数的工作原理,包括构造函数如何初始化对象属性,以及析构函数如何清理资源。此外,还探讨了在继承结构中构造函数和析构函数的调用顺序。

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

实例:

#include <iostream>
using namespace std;
class parent{
public:
	parent(int a, int b, int d)
	{
		this->a = a;
		this->b = b;
		this->d = d;
		cout << "基类构造" << endl;
	}
	~parent()
	{
		cout << "基类析构" << endl;
	}
public:
	int a;
private:
	int b;
protected:
	int d;
};
class child3 : public parent
{
public:
	child3(int c, int a, int b, int d) : parent(a, b, d)
	{
		this->c = c;
		cout << "派生类构造函数" << endl;
	}
	~child3()
	{
		cout << "派生类析构函数" << endl;
	}
public:
private:
	int c;
protected:
};
int main()
{
	{
		child3 oop(1, 2, 3, 3);
	}
	system("pause");
	return 0;
}

在上述代码中,程序在执行时会先进入到基类的构造函数执行parent(int a,int b,int c)构造函数,当构造函数执行结束后打印基类构造函数,然后继续执行child3的构造函数child3(int c,int a,int b,int  d),当该构造函数执行结束后打印派生类构造函数,然后进入到派生类析构函数执行,执行完成最后执行基类析构函数,最后打印基类析构函数;



混搭情况下构造和析构函数的调用规则:

构造:先调用父类构造函数,在调用构造成员,最后调用自己的构造函数;

析构:先析构自己,在析构成员变量,最后析构父类


#include <iostream>
using namespace std;
class Grad{
public:
	Grad(int _a, int _b)
	{
		this->_a = _a;
		this->_b = _b;
		cout << "Grad 构造函数" << endl;
	}
	~Grad()
	{
		cout << "Grad析构函数" << endl;
	}
private:
	int _a;
	int _b;
};
class parent 
{
public:
	parent(int a, int b, int d) 
	{
		this->a = a;
		this->b = b;
		this->d = d;
		cout << "基类构造" << endl;
	}
	~parent()
	{
		cout << "基类析构" << endl;
	}
public:
	int a;
private:
	int b;
protected:
	int d;
};
class child3 : public parent
{
public:
	child3(int c, int a, int b, int d) : parent(a, b, d), oop1(5, 6), oop2(7,8)
	{
		this->c = c;
		cout << "派生类构造函数" << endl;
	}
	~child3()
	{
		cout << "派生类析构函数" << endl;
	}
public:
	Grad oop1;
	Grad oop2;
private:
	int c;
protected:
};
int main()
{
	{
		child3 oop(1, 2, 3, 3);
	}
	system("pause");
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值