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

时间:2013-07-11 20:34:40

标签: 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;
}

3 个答案:

答案 0 :(得分: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 );
    ...
}

在主要功能中,您可以使用func成员函数以及func2func3func4

答案 1 :(得分:1)

function()必须声明为static才能使其正常工作。如果你在一个类中放置一个非静态成员函数,它就与该类的特定实例相关联。

答案 2 :(得分:1)

如果你想定义一个可以映射C函数和C ++成员函数的API,请按如下所示定义进程,并使用绑定来传递成员函数....

注意:未经测试(我在手机上!)

 class A {
 public:
     void func(int);
     static void StaticWrapper(A* ptr, int i)
     { ptr->func(i);}
...
};

 typedef  void (CStyleCB*)(int);


  int process( CStyleCB p, int x)
  {
      return (*p)(x);
  }

  int main()
  {
      A a;
      process( bind(&A::StaticWrapper, this, _1),   1 );
       ...
    }
相关问题