您的位置:首页 > 编程语言 > C语言/C++

C++中如何在main函数体为空的情况打印出字符串"GeeksforGeeks"

2016-04-11 12:20 302 查看


     C++中在main函数体为空的情况打印出字符串"GeeksforGeeks"

                       本文翻译自:http://www.geeksforgeeks.org/print-geeksforgeeks-empty-main-c/
                                                                         translated  By qiaghaohao 

                 正文:

                          写一个C++程序,在main函数体为空的情况下打印出字符串"GeeksforGeeks"。不允许在
  main函数中写任何语句。
                 
                 一种方法是给一个函数应用构造函数属性,使得此函数在main函数之前执行,代码如下:
#include <iostream>
using namespace std;

/* Apply the constructor attribute to myStartupFun() so that it
is executed before main() */
void myStartupFun (void) __attribute__ ((constructor));

/* implementation of myStartupFun */
void myStartupFun (void)
{
cout << "GeeksforGeeks";
}

int main ()
{

}



              以上方法只在GCC编译器上有效,下面是另一个有趣的方法来实现此功能,代码如下:

#include <iostream>
using namespace std;

class MyClass
{
public:
MyClass()
{
cout << "GeeksforGeeks";
}
}m;

int main()
{

}
       这个方法的思想是产生一个类,在构造函数中包含一个cout声明,然后一个定义类的全局对象。当对象被创建
  时,构造函数被调用,从而打印出了"GeeksforGeeks"。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息