构造函数的调用顺序:基类 --> 数据成员类对象(基于声明的顺序) --> 子类;
析构函数的调用顺序则相反。
#include<iostream>
using namespace std;
class human
{
public:
human(int height=0, int weight=0)
{
this->m_nHeight=height;
this->m_nWeight=weight;
cout<<"基类构造函数:human construct"<<endl;
}
~human()
{
cout<<"基类析构函数:human destruct"<<endl;
}
void eat()
{
cout<<"human eat"<<endl;
}
void sleep()
{
cout<<"human sleep"<<endl;
}
void breathe()
{
cout<<"human breathe"<<endl;
}
protected:
int m_nHeight,m_nWeight;
};
class tool
{
public:
tool()
{
cout<<"工具类tool:构造函数"<<endl;
this->m_nName=-1;
this->m_nPrice=-1;
};
~tool(){cout<<"工具类tool:析构函数"<<endl;};
protected:
int m_nPrice;
int m_nName;
};
class tool2
{
public:
tool2()
{
cout<<"工具类tool2:构造函数"<<endl;
this->m_nName=-2;
this->m_nPrice=-2;
};
~tool2(){cout<<"工具类tool2:析构函数"<<endl;};
protected:
int m_nPrice;
int m_nName;
};
class male:public human
{
public:
male()
{
m_nKind = -3;
cout<<"子类构造函数:male construct"<<endl;
}
~male()
{
cout<<"子类析构函数:male destruct"<<endl;
}
protected:
int m_nKind;
tool2 m_t2;
tool m_t;
};
int main(int argc,char* argv[])
{
male f;//此处开始调动相关构造函数
return 1;
}
//控制台输出如下:
//基类构造函数:human construct
//工具类tool2:构造函数(以类B、C对象作为类A的数据成员,则类对象B、C构造函数的调用顺序与该类数据成员在类A中声明顺序相关)
//工具类tool:构造函数
//子类构造函数:male construct
//子类析构函数:male destruct
//工具类tool:析构函数
//工具类tool2:析构函数
//基类析构函数:human destruct
可以看出: 默认构造函数或者是带默认参数的构造函数不仅对它本身、而且对复用它的其他类(子类或数据成员)都是及其关键的。