0

下面是我的程序。

  void fun1(void);
  int main(int argc, char *argv[])
  {
    cout<<"In main"<<endl;
    atexit(fun1);              //atexit calls the function at the end of main
    cout<<"Exit main"<<endl;
    return 0;
  }
  void fun1(void)
  {
    cout<<"fun1 executed"<<endl;
  }

输出是

 In main
 Exit main
 fun1 executed

但我打算这样的输出:

 In main
 fun1 executed
 Exit main

我不想直接调用“fun1”函数或使用任何其他可以调用我的函数“fun1”的函数。

有什么办法可以实现这个输出吗?任何帮助都是最受欢迎的。

4

4 回答 4

2

没有。

只有atexit和静态对象破坏“自行”发生,并且这两种情况都发生在从main.

这是有道理的,当你想一想时:应该发生的事情main应该写在main. 如果您需要在给定时间调用一个函数,请将其写入您的程序。这就是你编写程序的目的。main适合您的程序。


很可能,使用“诡计”或“黑客”会让你被我的团队解雇。

于 2013-11-04T13:55:39.267 回答
0

这是使用范围的 hack:

#include <iostream>

class call_on_destructed {
private:
    void (*m_callee)();
public:
    call_on_destructed(void (*callee)()): m_callee(callee) {}
    ~call_on_destructed() {
        m_callee();
    }
};

void fun() {
    std::cout << "fun\n";
}

int main() {
    {
        call_on_destructed c(&fun);
        std::cout << "In main" << std::endl;
    }
    std::cout<<"Exit main"<<std::endl;
}

输出:

In main
fun
Exit main

作用域结束导致调用类析构函数,然后调用在类中注册的 fun 函数。

于 2013-11-04T14:12:08.563 回答
-1

你想要类似的东西:

  void fun1(void)
  {
    std::cout << "fun1 executed" << std::endl;
  }

  void call(void f())
  {
      f();
  }

  int main(int argc, char *argv[])
  {
    std::cout << "In main" << std::endl;
    call(fun1);              //call calls the given function directly
    std::cout << "Exit main" << std::endl;
    return 0;
  }
于 2013-11-04T14:01:12.527 回答
-1

显然,如果你想让你的函数执行,就会调用它!也就是说,调用你的函数而不调用你的函数是行不通的。atexit()也只是调用你的函数:你注册最终被调用的内容。

从它的声音来看,您的任务要求传递一个函数对象并让该工具调用您的函数。例如,您可以使用函数调用者:

template <typename F>
void caller(F f) {
    f();
}

int main() {
    std::cout << "entering main\n";
    caller(fun1);
    std::cout << "exiting main()\n";
}

显然,虽然没有提到那个名字,caller()但确实打电话。fun1

于 2013-11-04T14:04:14.673 回答