C++学习笔记2---继承

内存对象模型,讲述构造函数和析构函数的调用

代码

#include<iostream>
using namespace std;

/***********************************************/
class GrandFatherOne
{
public:
	int i;
	GrandFatherOne();
	GrandFatherOne(int i);
	~GrandFatherOne();
	void Print();
};

GrandFatherOne::GrandFatherOne()
{
	this->i = 0;
	cout<<"GrandFather's default construct function is called!"<<endl;
}

GrandFatherOne::GrandFatherOne(int i)
{
	this->i = i;
	cout<<"GrandFather's constructer function with arguement is called!"<<endl;
}

void GrandFatherOne::Print()
{
	cout<<"GrandFatherOne's Print "<<this->i<<endl;
}


GrandFatherOne::~GrandFatherOne()
{
	cout<<"GrandFatherOne's disConstructer function is called!"<<endl;
}

/***********************************************/
class FatherOne:public GrandFatherOne
{
public:
	int i;
	FatherOne();
	FatherOne(int i);
	~FatherOne();
	void Print();
};

FatherOne::FatherOne()
{
	this->i = 1;
	cout<<"FatherOne's  default constructer function !"<<endl;
}

FatherOne::FatherOne(int i)
{
	this->i = i;
	cout<<"FatherOne's construct function with arguement  !"<<endl;
}

FatherOne::~FatherOne()
{
	cout<<"FatherOne disContruct's funtions is called!"<<endl;
}

void FatherOne::Print()
{
	cout<<"FatherOne's Print "<<this->i <<endl;
}
/***********************************************/

class Son:public FatherOne
{
public:
	int i;
public:
	Son();
	Son(int i);
	~Son();
	void Print();
};

Son::Son(int i)
{
	this->i = i;
	cout<<"Son's constructer function with arguement is called!"<<endl;
}

Son::Son()
{
	this->i = 2;
	cout<<"Son's constructer function!"<<endl;
}

Son::~Son()
{
	cout<<"Son's Discontructer is called!"<<endl;
}
void Son::Print()
{
	cout<<this->i<<endl;
	cout<<"FatherOne's i\t";
	cout<<FatherOne::i<<endl;
}

int main()
{
	Son s1;
	return 0;
}

输出


继承关系                                                                                  内存模型


如图所示,为此时类的内存模型,所以,构造函数先构造GrandFather,然后是FatherOne,最后是Son,析构的顺序恰好相反。

访问层次,从内存模型可以看出,Son的对象保存有GrandFather 以及FatherOne的内存的空间,所以通过域作用符(::)可以访问到父类,甚至祖父类的成员变量

以上是单一继承,接下来在看看多重继承的情况

继承关系                                                                  内存模型


输出


当继承关系为虚继承时

class FatherOne:virtual public GrandFatherOne
class FatherTwo:virtual public GrandFatherOne

 内存模型 


输出情况


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值