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
總結:
由上述的結果可以看出,構造函數的調用是以從數組的低地址變量向高地址變量的順序進行的。當退出局部棧時,析構函數的調用是以從高地址變量向低地址變量的順序進行的。