[C++基础]008_类的构造函数和析构函数

 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 }

上面的代码输出 什么呢?如下:

constrct
constrct
destruct
请按任意键继续. . .

为毛只有一个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 }

输出如下:

constrct
destruct
constrct
destruct
请按任意键继续. . .

看到了吧,在调用test()之后,析构函数被调用了.

posted @ 2012-10-09 00:47  邵贤军  阅读(490)  评论(1编辑  收藏  举报