内存对象模型,讲述构造函数和析构函数的调用
代码
#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
内存模型
输出情况