C++基类指向派生类的析构顺序

// An highlighted block
#include<iostream>
#include<vector>
using namespace std;
int i = 0;
class A
{
public:
	A()
	{
		cout << "父类构造函数" << endl;
	}
	A(int value) :a(value)
	{
		cout << "父类构造函数2" << endl;
	}
	void getchar()
	{
		cout << "调用父类函数" << endl;
	}
	virtual int getindex()
	{
		cout << a << endl;
		return a;
	}
	~A()
	{
		cout << "父类析构函数" <<i++<< endl;
	}
private :
	int a =0;

};
class B :public A
{
public:
	B()
	{
		cout << "子类构造函数" << endl;
	}
	void getchar()
	{
		cout << "调用子类函数" << endl;
	}
	virtual int getindex()
	{
		cout << "调用子类函数" << endl;
		cout << b << endl;
		return b;
	}
	~B()
	{
		cout << "子类析构函数" << endl;
	}
private:
	int b=1;
	int a = 0;
};
int main()
{
	A *a;
	
	a = new B[2];
	cout << "------" << endl;
	
	cout << "------" << endl;

	cout << "------" << endl;
	a->getindex();
	a->getchar();
	delete []a;

	system("pause");
	return 0;

}

1,当基类指针指向派生类的时候,构造函数,会首先构造父类构造函数,再构造子类构造函数,而在析构时,只析构父类的析构函数,,
基类构造–》子类构造–》基类析构。
2,当派生类指针指向派生类的时,基类构造–》子类构造–》子类析构–》基类析构。
3,当基类指针指向派生类的时,如果类函数为是虚函数的时候,则访问派生类的函数,
如果类函数不是虚函数,则调用基类函数。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值