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()之后,析构函数被调用了.

相关文章:

  • 2021-06-29
  • 2022-01-02
猜你喜欢
  • 2021-06-04
  • 2021-11-05
  • 2021-06-29
  • 2021-11-25
  • 2022-12-23
  • 2021-12-03
  • 2021-09-24
相关资源
相似解决方案