类型 x 的 c++ 参数与带 atexit 的类型的参数不兼容

c++ argument of type x is incompatible with parameter of type with atexit

当我尝试 运行 std 中带有 theatexti() 的函数时出现此错误。我不明白错误。

这里是错误:

 IntelliSense: argument of type "void (Demo3Main::*)()" is incompatible with parameter of type "void (__cdecl *)()"

这是代码:

Demo3Main::Demo3Main(void)
: BaseEngine( 50 )
{
    atexit(RestorScore);
}

void Demo3Main::RestorScore(){
    std::ofstream outfile("old_score.txt");
    int num1 = 0;
    outfile << num1;
    outfile.close();
}

ELI5版本

atexit 的回调规范是

void (*function)(void)

这意味着您必须在表单上传递一个函数:

void my_function()
{
}

但是,您传递了一个具有不同类型的 class 成员函数。它的类型是:

 void (Demo3Main::*)()

您可以通过在 class 外部编写函数来使您的程序运行。例如:

void RestorScore(){
   std::ofstream outfile("old_score.txt");
   int num1 = 0;
   outfile << num1;
}
atexit(RestoreScore);