c ++:成员函数作为另一个函数的参数

Pab*_*era 2 c++ function member-functions

我试图将一个函数从类传递给其他函数参数.我收到这个错误.

错误:类型'void(A_t ::)(int)'的参数与'void(*)(int)'不匹配

有没有办法管理这个,仍然使用类a中的函数.提前致谢.

#include <iostream>

using namespace std;

void procces(void func(int x),int y);

class A_t
{
   public:
      A_t();
      void function(int x)
      {
          cout << x << endl;
      }
};

int main()
{
   A_t a;

   procces(a.function,10);
}

void procces(void func(int x),int y)
{
    func(y);
    return;
}
Run Code Online (Sandbox Code Playgroud)

Pie*_*aud 5

以下是如何使用指向函数指针的示例:

class A_t {
public:
    void func(int);
    void func2(int);
    void func3(int);
    void func4(int);
    ...
};

typedef  void (A_t::*fnPtr)(int);


int process(A_t& o, fnPtr p, int x)
{
    return ((o).*(p))(x);
}

int main()
{
    fnPtr p = &A_t::func;
    A_t a;
    process( a, p, 1 );
    ...
}
Run Code Online (Sandbox Code Playgroud)

在main函数中,您可以使用func成员函数以及func2,func3func4.