码迷,mamicode.com
首页 > 编程语言 > 详细

C++ Primer Plus学习笔记之继承类的初始化顺序

时间:2014-05-04 09:41:27      阅读:373      评论:0      收藏:0      [点我收藏+]

标签:c++ primer plus   派生   

C++ Primer Plus学习笔记之继承类的初始化顺序

基类的构造函数,析构函数和操作符函数operator=是不能被派生类继承的;
那么,当创建一个派生类对象时,怎样调用基类的构造函数对基类的数据进行初始化呢???
答案是:构造函数执行时遵行先兄长(基类),再客人(对象成员),后自己(派生类)的顺序;
另一方面,执行析构函数时,先执行派生类的析构函数,再执行基类的析构函数。原因是,对基类的破坏隐含了对派生类的破坏,所以派生类的析构函数必须先执行;
#include<iostream>

using namespace std;

class Member
{
	public:
		Member()
		{
			cout<<"Member created"<<endl;
		}
		~Member()
		{
			cout<<"Member destroyed"<<endl;
		}
};

class Base
{
	public:
		Base()
		{
			cout<<"Base created"<<endl;
		}
		~Base()
		{
			cout<<"Base destroyed"<<endl;
		}
};

class Derived:public Base
{
	public:
		Derived()
		{
			cout<<"Derived created"<<endl;
		}
		~Derived()
		{
			cout<<"Derived destroyed"<<endl;
		}
	private:
		Member m;
};

int main(int argc,char *argv[])
{
	Derived d;

	return 0;
}
运行结果:

Base created

Member created

Derived created

Derived destroyed

Member destroyed

Base destroyed


C++ Primer Plus学习笔记之继承类的初始化顺序,布布扣,bubuko.com

C++ Primer Plus学习笔记之继承类的初始化顺序

标签:c++ primer plus   派生   

原文地址:http://blog.csdn.net/cstopcoder/article/details/24935127

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!