使用特定格式输出从 Main 间接调用函数
calling a function indirectly from main with an particular format output
这是我下面的程序。
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
尽管没有提到这个名字。
相关文章:
- 当我尝试在 Main 中调用插入函数时,它不是取数字?
- 未声明的标识符和类型"int"从 main 调用类时出现意外错误
- 如何使 WaitForSingleObject 在从 main 调用的线程内接收信号作为类成员函数
- C++尝试从main调用函数
- 如何用相同的签名从main调用基类函数
- C++ 如何从 main 调用派生的基类函数
- 读取函数由 main 调用,但不执行
- 如果方法私有,是否可以从 main 调用该方法?如果不是,怎么可能
- 使用类通过main调用函数
- 如果没有返回,如何向main调用void函数
- 在C++中从Main调用函数
- C++ 从实现文件中的 main 调用函数
- 从main调用c++源文件中的函数
- 如何在另一个包含对象的文件中创建一个函数并从 main 调用它
- 是否可以从常规main调用WinMain ?
- c++:从main()调用模板化函数
- 从c++中的main调用类中的结构体
- 在类中从main调用函数
- 未在作用域内声明的c++类——从main调用
- 如何编写函数并从main调用它们