使用特定格式输出从 Main 间接调用函数

calling a function indirectly from main with an particular format output

本文关键字:Main 调用 函数 输出 定格 格式      更新时间:2023-10-16

这是我下面的程序。

  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"的函数。

有什么方法可以实现此输出吗?欢迎任何帮助。

No

.

只有atexit和静态物体的破坏才会"自行"发生,而这两件事都是在从main回来后发生的。

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


可能,通过"技巧"或"黑客",会让你被我的团队解雇。

这是一个使用示波器的黑客:

#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 << "funn";
}
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 函数。

你想要这样的东西吗:

  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;
  }

显然,如果你想执行你的函数,有些东西会调用它!也就是说,在不调用函数的情况下调用函数将不起作用。 atexit()也只是调用你的函数:你注册最终被调用的内容。

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

template <typename F>
void caller(F f) {
    f();
}
int main() {
    std::cout << "entering mainn";
    caller(fun1);
    std::cout << "exiting main()n";
}

显然,caller()确实称呼fun1尽管没有提到这个名字。