析構函數按照與C++中對象創建相反的順序調用,但我不明白爲什麼它沒有爲對象數組維護。爲什麼析構函數不按相反順序調用對象數組?
#include <iostream>
using namespace std;
class test {
int nmbr;
static int c;
public:
test(int j)
{
cout<<"constructor is called for object no :"<<j<<endl;
nmbr=j;
};
~test()
{
c++;
cout<<"destructor is called for object no :"<<c<<endl;
};
};
int test::c=0;
int main()
{
test ob[]={test(1),test(2),test(3)};
return 0;
}
上述程序輸出
constructor is called for object no :1
constructor is called for object no :2
constructor is called for object no :3
destructor is called for object no :1
destructor is called for object no :2
destructor is called for object no :3
但爲什麼析構函數不按相反的順序叫什麼?
嘗試'測試ob [] = {測試(97),測試(1043),測試(-12)};'看看會發生什麼。 – molbdnilo
或設置test :: c = 5或0以外的任意隨機數。你會明白 –