1 #include<iostream> 2 using namespace std; 3 4 class Human{ 5 public: 6 Human(){ 7 cout<<"constrct"<<endl; 8 } 9 ~Human(){10 cout<<"destruct"<<endl;11 }12 private:13 int age;14 };15 16 int main(){17 Human human;18 19 Human *humanPtr;20 humanPtr = new Human();21 delete humanPtr;22 23 system("pause");24 return 0;25 }
上面的代碼輸出 什麼呢?如下:
constrctconstrctdestruct請按任意鍵繼續. . .
為毛只有一個destruct呢?難道第一個對象不析構嗎?不是的!在main函數執行return的時候,解構函式就會被調用了.
不信,看如下代碼:
1 #include<iostream> 2 using namespace std; 3 4 class Human{ 5 public: 6 Human(){ 7 cout<<"constrct"<<endl; 8 } 9 ~Human(){10 cout<<"destruct"<<endl;11 }12 private:13 int age;14 };15 16 int test(){17 Human human;18 return 0;19 }20 21 int main(){22 23 test();24 25 Human *humanPtr;26 humanPtr = new Human();27 delete humanPtr;28 29 system("pause");30 return 0;31 }
輸出如下:
constrctdestructconstrctdestruct請按任意鍵繼續. . .
看到了吧,在調用test()之後,解構函式被調用了.