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

时间:2014-05-04 09:41:27   收藏:0   阅读:373

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

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!