我在析構函數上做過實踐,但編譯這個程序時我不知道爲什麼輸出不如我想的那樣。析構函數如何執行?
#include <iostream>
using namespace std;
class aaa
{
private:
static int x;
int code;
public:
/*after constructor executes 3 times the value of "code" becomes 103*/
aaa()
{
code=x;
cout<<"Default Constructor"<<endl;
x++;
}
~aaa()
{
cout<<"Destructor of "<<code<<endl;
}
};
int aaa::x=101;
int main()
{
aaa *p;
p=new aaa[3];
delete []p;
return 0;
}
輸出是:
Default Constructor
Default Constructor
Default Constructor
Destructor of 103
Destructor of 102
Destructor of 101
,而我認爲這將是這樣的:
101
102
103
以及如果我寫delete p而不是delete [] p會發生什麼,因此很多時候Destructor是叫 –
@AmanWarudkar https://stackoverflow.com/questions/6953457/delete-and-delete-are-the-same-when-deleting-arrays – Curious
@AmanWarudkar更新了我的答案,希望這有助於!不要忘記*接受*答案。好奇的感謝鏈接和很好的答案順便說一句。 – gsamaras