_onexit函数的使用 完成主函数执行完毕后再执行一段程序

4690阅读 0评论2013-04-05 tjnulql
分类:C/C++


点击(此处)折叠或打开

  1. #include <iostream>
  2. #include <cstdlib>

  3. using namespace std;

  4. //_onexit 包含在cstdlib中,是c语言中的库函数
  5. //_onexit Callback函数必须是带有int类型返回值的无参数函数
  6. //_onexit 无论_onexit函数放到main中哪个位置相应的Callback都是最后执行
  7. //_onexit 如果有多个_onexit, 则Callback的执行顺序跟注册顺序相反

  8. int func1();
  9. int func2();
  10. int func3();

  11. int main(int argc,char * argv[])
  12. {
  13.     _onexit(func1);
  14.     cout<<"Line1 in main..."<<endl;
  15.     _onexit(func2);
  16.     cout<<"Line2 in main..."<<endl;
  17.     _onexit(func3);
  18.     cout<<"Line3 in main..."<<endl;
  19. }

  20. int func1()
  21. {
  22.     cout<<"I am onexit_Function1"<<endl;
  23.     return 0;
  24. }
  25. int func2()
  26. {
  27.     cout<<"I am onexit_Function2"<<endl;
  28.     return 0;
  29. }
  30. int func3()
  31. {
  32.     cout<<"I am onexit_Function3"<<endl;
  33.     return 0;
  34. }


  35. /*
  36. 输出如下:
  37. Line1 in main...
  38. Line2 in main...
  39. Line3 in main...
  40. I am onexit_Function3
  41. I am onexit_Function2
  42. I am onexit_Function1
  43. */

上一篇:面试中遇到的阶层问题1000!
下一篇:文件操作 完成从一个文件中读入数据排序后输出到另一个文件