C++函数指针类型与 Linux 和 VMS 上的候选指针类型不兼容



这个问题与我的另一个问题有关 - boost::bind 返回一个函数对象,它是需要指针的函数的参数

除了接口

bridge_set_pound_var_func

不允许更改。

此外,boost::functionboost::bind不能很好地处理大型项目。

我的新代码如下:

#include <iostream>
class myA
{
 public:
 int bridge_set_pound_var_func(int (*fp)(const char *, char *, void *), void *arg)
 {
     void * b = NULL;
     int a = fp("this is poundVar", "ths is t1", b) ;
     std::cout << "bridge_set_pound_var_func is called "<< " , a is " << a << std::endl ;
     return 0;
 }
};
class myC
{
public:
myA *myOA;
int func(const char * poundVar , char * t1, void * t2);
int myCCall()
{
    myA myAO;
    myOA = &myAO;
    std::cout << "myCCall is called " << std::endl;
    myOA->bridge_set_pound_var_func( &myC::func, (void *)this );
    return 0;
 }
};
int myC::func(const char * poundVar , char * t1, void * t2)
{
 std::cout << "myC::func is called " << std::endl;
 return 1;
}
int main()
{
  myC myCO ;
  myC *m1p = &myCO ;
  m1p->myCCall() ;
  return 0 ;
}
// EOF

Linux 上的错误:

  In member function 'int myC::myCCall()':
  error: no matching function for call to 'myA::bridge_set_pound_var_func(int (myC::*)(const char*, char*, void*), void*)'
  candidates are: int myA::bridge_set_pound_var_func(int (*)(const char*, char*, void*), void*)

虚拟机上的错误:

 In member function 'int myC::myCCall()':
 error: no matching function for call to 'myA::bridge_set_pound_var_func(int (myC::*)(const char*, char*, void*), void*)'
 candidates are: int myA::bridge_set_pound_var_func(int (*)(const char*, char*, void*), void*)

简短的回答是:指向成员函数的指针不是指向函数的指针。前者需要知道他们被调用的对象,后者不需要。使用的典型方法是使用通常存在的"用户数据"void*指向合适的基类,强制转换指针并调用相应的虚函数。在那里,您可以轻松恢复必要的对象上下文。

最新更新