无法将参数 1 从"int (__thiscall A::* *)(void)"转换为"int (__cdecl *)(void)"

Cannot convert parameter 1 from 'int (__thiscall A::* *)(void)' to 'int (__cdecl *)(void)'

本文关键字:void int cdecl 转换 参数 thiscall      更新时间:2023-10-16

我在运行此代码时收到此错误。请查看我的代码并协助我。

#include "stdafx.h"
#include <iostream>
class A
{
  public:
    void PrintTwoNumbers(int (*numberSource)(void)) 
    {
      int val1= numberSource();     
    }
    int overNineThousand(void) 
    {
      return (rand()%1000) + 9001;
    }        
};
int _tmain(int argc, _TCHAR* argv[])
{ 
  int (A::*fptr) (void) = &A::overNineThousand;
  int (A::*fptr1) (void);
  fptr1 = &A::overNineThousand;
  A a;
  a.PrintTwoNumbers(&fptr); //-> how to pass here
  getchar();
  return 0; 
}

我厌倦了在网上搜索这个,没有人为此提供完美的解决方案。任何人都可以将此代码编辑为工作代码并帮助我吗?

预期的参数是一个(非成员(函数指针。而是传递指向成员函数的(指向 a( 指针。(指向(指向成员函数的指针不能转换为指向(非成员(函数的指针。

可能最简单的解决方案是将函数参数固定为正确的类型,传递隐式对象参数,并且在调用时不要获取成员函数指针的地址。

void PrintTwoNumbers(int (A::*numberSource) ()) 
{
  int val1= (this->*numberSource)();
}
a.PrintTwoNumbers(fptr);