吾爱程序员:这里有好玩的游戏和软件
当前位置:首页C语言教程 → main() 中的 return 语句与 exit()

main() 中的 return 语句与 exit()

来源:网络 | 更新时间:2022-01-14 20:25:54
在 C++ 中, exit(0)return 0有什么区别? exit(0)用于退出程序时,不会调用局部范围的非静态对象的析构函数。但是如果使用 return 0,则调用析构函数。 程序1————使用exit(0)退出
#include<iostream>
#include<stdio.h>
#include<stdlib.h>

using namespace std;

class Test {
public:
Test() {
printf("Inside Test's Constructorn");
}

~Test(){
printf("Inside Test's Destructor");
getchar();
}
};

int main() {
Test t1;

// using exit(0) to exit from main
exit(0);
}
输出: Inside Test’s Constructor 程序 2 – 使用 return 0 退出
#include<iostream>
#include<stdio.h>
#include<stdlib.h>

using namespace std;

class Test {
public:
Test() {
printf("Inside Test's Constructorn");
}

~Test(){
printf("Inside Test's Destructor");
}
};

int main() {
Test t1;

// using return 0 to exit from main
return 0;
}
输出: Inside Test’s Constructor Inside Test’s Destructor 调用析构函数有时很重要,例如,如果析构函数具有释放资源(如关闭文件)的代码。 请注意,即使我们调用 exit(),静态对象也会被清除。例如,请参阅以下程序。
#include<iostream>
#include<stdio.h>
#include<stdlib.h>

using namespace std;

class Test {
public:
Test() {
printf("Inside Test's Constructorn");
}

~Test(){
printf("Inside Test's Destructor");
getchar();
}
};

int main() {
static Test t1; // Note that t1 is static

exit(0);
}
输出: Inside Test’s Constructor Inside Test’s Destructor  

最新文章

热点资讯

手游排行榜

CopyRight 2020-2030吾爱程序员

鄂ICP备2021004581号-8

本站资源收集于网络,如有侵权请联系我们:35492删除0109@qq.com