今天面试遇到一个问题,没答上来,特此记录一下。
问题是:如何在main()前面或后面调用自己的函数?
参考文章http://gujiaxi.github.io/blog/2012/05/21/zai-main-qian-slash-hou-diao-yong-han-shu/后得出一下代码
注:该文章最后一部分应该属于笔误,实际上是在main()后面调用函数
<!-- lang: cpp -->
#include <stdio.h>
void befor()
{
printf("hello, before main\n");
}
void after()
{
printf("hello, after main\n");
}
namespace
{
struct _caller
{
_caller() { befor(); }
~_caller() { after(); }
} caller;
}
int main()
{
printf("hello, world\n");
return 0;
}
输出结果:
hello, before main
hello, world
hello, after main