首页 > 编程语言 > 详细

001_c++类成员变量初始化顺序及类析构顺序

时间:2021-08-11 23:52:53      阅读:24      评论:0      收藏:0      [点我收藏+]

初始化顺序

先上结论:
     当调用构造函数时,首先调用父类的构造函数,其次调用类成员变量的构造函数,最后调用当前类自身的构造函数.
     当调用析构函数时(析构函数必须添加 virtual 关键字),首先调用当前类对象的析构函数,其次调用类成员变量的析构函数,最后调用父类的析构函数。


     测试代码如下:

// 头文件
#ifndef _TEST_NEW_DELETE_ORDER_H_
#define _TEST_NEW_DELETE_ORDER_H_

#include <iostream>
using namespace std;

class People 
{
public:
	People()
	{
		cout << "on people construct" << endl;
	}

	virtual ~People()
	{
		cout << "on people destruct." << endl;
	}

	string name;
};

class Book
{
public:
	Book()
	{
		cout << "on book construct." << endl;
	}

	~Book()
	{
		cout << "on book destruct." << endl;
	}

};

class Student : public People 
{
public:
	Student()
		:m_book(new Book())
	{
		cout << "on student construct." << endl;
		cout << name.c_str();
	}

	virtual ~Student()
	{
		cout << "on student destruct." << endl;
		
		if (m_book)
		{
			delete m_book;
			m_book = nullptr;
		}
	}

private:
	Book *m_book;
};



#endif //_TEST_NEW_DELETE_ORDER_H_

测试 main 函数:

int main()
{
	People *stu = new Student();
	delete stu;
	getchar();
}

打印结果如下:
on people construct
on book construct.
on student construct.
on student destruct.
on book destruct.
on people destruct.

001_c++类成员变量初始化顺序及类析构顺序

原文:https://www.cnblogs.com/cpp-muggle/p/15129971.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!