C++类的数组中构造函数和析构函数的调用顺序(2)
对于如下的代码:
#includeusing namespace std;class CBase {private: static int count;public: int id;public: CBase() { id = CBase::count++; cout << "CBase():Constructor:" < << endl; } ~CBase() { cout << "CBase(): Destructor:" < << endl; }};int CBase::count = 0;//类的静态变量必须在类外以这样的方式进行初始化,否则会出现连接错误class CDerive :public CBase {public: CDerive() { cout << "CDerive():Constructor:" << id<
运行结果如下:
S:\ComputerTech\VS2015\Release>Test.exeCBase():Constructor:0CDerive():Constructor:0CBase():Constructor:1CDerive():Constructor:1CBase():Constructor:2CDerive():Constructor:2p[0].id=0p[1].id=1p[2].id=2&p[0]=004AFCB4&p[1]=004AFCB8&p[2]=004AFCBCCDerive(): Destructor:2CBase(): Destructor:2CDerive(): Destructor:1CBase(): Destructor:1CDerive(): Destructor:0CBase(): Destructor:0
总结:
由上述的结果可以看出,构造函数的调用是以从数组的低地址变量向高地址变量的顺序进行的。当退出局部栈时,析构函数的调用是以从高地址变量向低地址变量的顺序进行的。