在main()之前调用void函数 [英] Calling void function before main()

查看:326
本文介绍了在main()之前调用void函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否可以使用temp变量调用void函数.例如.在以下代码块中...

I wanted to know if it was possible to call a void function without using a temp variable. E.g. in the following code block...

#include <iostream>

void earlyInit()
{
  std::cout << "The void before the world." << std::endl;
}

int g_foo = (earlyInit(), 0);

int main( int argc, char* argv[] )
{
  std::cout << "Hello, world!" << std::endl;
}

...我不需要g_foo,宁愿它不存在.有没有一种方法可以在没有中间临时变量的情况下调用void函数?

...I have no need for g_foo and would rather it not exist. Is there a way to call void functions without an intermediate temp variable?

推荐答案

我想知道是否可以在不使用temp变量的情况下调用void函数.例如.在下面的代码块中.

I wanted to know if it was possible to call a void function without using a temp variable. E.g. in the following code block.

该语言不提供任何此类机制.正如其他答案所指出的那样,可能存在特定于编译器的方法.

The language does not provide any such mechanism. As other answers have pointed out, there maybe compiler-specific ways to do that.

但是,我认为您的方法没有任何问题.我经常使用以下模式.

However, I don't see anything wrong with your approach. I use the following pattern a lot.

#include <iostream>

namespace mainNS  // A file-specific namespace.
{
   void earlyInit()
   {
      std::cout << "The void before the world." << std::endl;
   }

   struct Initializer
   {
      Initializer();
   };
}

using namespace mainNS;
static Initializer initializer;

Initializer::Initializer()
{
   earlyInit();
   // Call any other functions that makes sense for your application.
}

int main( int argc, char* argv[] )
{
  std::cout << "Hello, world!" << std::endl;
}

这篇关于在main()之前调用void函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆