C++学习笔记(7)----类的数组中构造函数和析构函数的调用顺序

时间:2023-05-11 20:06:38

C++类的数组中构造函数和析构函数的调用顺序(2)

对于如下的代码:

#include<iostream>
using namespace std; class CBase {
private:
static int count;
public: int id;
public:
CBase() {
id = CBase::count++;
cout << "CBase():Constructor:" <<id<< endl;
}
~CBase() {
cout << "CBase(): Destructor:" <<id<< endl;
}
};
int CBase::count = 0;//类的静态变量必须在类外以这样的方式进行初始化,否则会出现连接错误 class CDerive :public CBase {
public:
CDerive() {
cout << "CDerive():Constructor:" << id<<endl;
}
~CDerive() {
cout << "CDerive(): Destructor:" <<id<< endl;
}
}; int main(int argc, char* argv[])
{
CDerive p[3];
cout << "p[0].id=" << p[0].id << endl;
cout << "p[1].id=" << p[1].id << endl;
cout << "p[2].id=" << p[2].id << endl;
cout << "&p[0]=" << &p[0] << endl
<< "&p[1]=" << &p[1] << endl
<< "&p[2]=" << &p[2] << endl;
return 0;
//当函数退出时,栈中的类的实例会自动调用析构函数,我们通过此例来查看它们调用的顺序
}

运行结果如下:

S:\ComputerTech\VS2015\Release>Test.exe
CBase():Constructor:0
CDerive():Constructor:0
CBase():Constructor:1
CDerive():Constructor:1
CBase():Constructor:2
CDerive():Constructor:2
p[0].id=0
p[1].id=1
p[2].id=2
&p[0]=004AFCB4
&p[1]=004AFCB8
&p[2]=004AFCBC
CDerive(): Destructor:2
CBase(): Destructor:2
CDerive(): Destructor:1
CBase(): Destructor:1
CDerive(): Destructor:0
CBase(): Destructor:0

总结:

由上述的结果可以看出,构造函数的调用是以从数组的低地址变量向高地址变量的顺序进行的。当退出局部栈时,析构函数的调用是以从高地址变量向低地址变量的顺序进行的。