指向成员功能的功能指针

Function pointer pointing to member function

本文关键字:功能 指针 成员      更新时间:2023-10-16

我很难创建一个普通的旧功能指针,并将其分配给 myClass 对象 obj 的成员函数。我在下面复制了一个样本,

class myclass
{
public:
myclass() { i = 38; }
int i;
void func() { cout << "inside func" << endl;  }
};
int main()
{
    myclass obj;
    myclass *objptr = &obj;
    int myclass::*iptr1; //decl pointer to member
    iptr1 = &myclass::i; //obtain offset
    cout << obj.*iptr1 << endl; //dereference using object; use .*
    cout << objptr->*iptr1 << endl; //dereference using pointer to object; use ->* 
    int *iptr2; //decl plain old integer pointer
    iptr2 = &obj.i; //obtain address of member
    cout << *iptr2 << endl; //dereference
    void(myclass::*fptr1)(); //decl pointer to member 
    fptr1 = &myclass::func; //obatain offset
    (obj.*fptr1)(); //dereference using object; use .*
    (objptr->*fptr1)(); //dereference using pointer to object; use ->* 
    /*void(*fptr2) (); // decl plain old function pointer
   fptr2 = obj.func; //this is the exact line that doesn't compile
   (*fptr2) ();*/ //after having a pointer to the member function *func* I would like to call it like this, if possible, from this plain old pointer
   getchar();
   return 0;
}

我会出现以下错误,如果三行不被选中

Error   C3867   'myclass::func': non-standard syntax; use '&' to create a 
pointer to member   
Error   C2440   '=': cannot convert from 'void (__thiscall myclass::* )
(void)' to 'void (__cdecl *)(void)'

如果不是三行,我得到了预期的输出

38
38
38
inside func
inside func

我需要使用普通的旧功能指针而不是类成员功能的指针来获取Func 内部的第三个。需要一些帮助。我在这里缺少语法吗?!

func是一个非静态成员函数。它需要一个 myclass对象才能在功能上操作(函数内的this然后指向(。好像该函数具有无形的myclass参数。

fptr2是一个函数的函数指针,无需任何参数,因此拒绝了分配。这是一些替代解决方案:

  • 使func静态。
  • fptr2的类型更改为指针到会员。
  • 请勿使用原始功能指针;切换到C 11 lambdas和/或std::function

这是后者的一个示例:

std::function<void()> f2;
f2 = [&]{ obj.func(); };
f2();