[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()之后,析构函数被调用了.
原文链接: https://www.cnblogs.com/alephsoul-alephsoul/archive/2012/10/09/2716008.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/65228

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月9日 上午11:44
下一篇 2023年2月9日 上午11:44

相关推荐