当某个类既有基类,又有对象数据成员时,在调用该类的构造函数时,包括基类的构造函数和对象数据成员的构造函数在内的构造函数的调用如下:
- 调用基类的构造函数,其调用顺序按照继承操作时在冒号后面给出的基类排列顺序,如果基类中还包括对象数据成员,则先调用对象成员的构造函数,然后再执行相应的基类的构造函数体。
- 调用对象数据成员的构造函数,其调用顺序按照他们在类中的定义顺序。
- 执行本类的构造函数体。
/*分析构造函数和析构函数的执行过程*/
#include<iostream>
using namespace std;
class test1
{
public:
test1()
{
cout<<"enter test1 constructor"<<endl;
}
~test1()
{
cout<<"enter test1 destructor"<<endl;
}
};
class test2
{
public:
test2()
{
cout<<"enter test2 constructor"<<endl;
}
~test2()
{
cout<<"enter test2 destructor"<<endl;
}
};
class test3
{
test1 x;
public:
test3()
{
cout<<"enter test3 constructor"<<endl;
}
~test3()
{
cout<<"enter test3 destructor"<<endl;
}
};
class test4
{
test2 y;
public:
test4()
{
cout<<"enter test4 constructor"<<endl;
}
~test4()
{
cout<<"enter test4 destructor"<<endl;
}
};
class test5:public test3,public test4
{
test1 x1;
test1 x2;
test2 y1;
test2 y2;
public:
test5()
{
cout<<"enter test5 constructor"<<endl;
}
~test5()
{
cout<<"enter test5 destructor"<<endl;
}
};
int main()
{
test5 dt;
}