简体   繁体   English

将函数名称作为C ++类中另一个函数的参数传递

[英]Passing function name as parameter of Another function in C++ class

I have two classes A and B. I want to pass a function name in class A as parameter of function in Class B. I tried with below sample, Is it correct way. 我有两个类A和B。我想在A类中传递一个函数名称作为B类中函数的参数。我尝试了以下示例,这是正确的方法吗?

class A
{
  public:
  B m_b;

  void MyFun()
  {
      // do something
  }

  void Test()
  {
  m_b.Process( MyFun );
  } 
}


class B
{
 public:
 void Process( void (*f)() )
 {
   (*f)();
 }
}

thanks in advance 提前致谢

Since MyFun is a member function of class A , you need a pointer-to-member instead of a regular function pointer, and you also need an instance of class A to invoke the function on: 由于MyFun是类A的成员函数,因此您需要一个指向成员的指针而不是常规函数指针,并且还需要类A的实例才能在以下位置调用该函数:

class B
{
 public:
 void Process(A *obj, void (A::*f)() )
 {
   (obj->*f)();
 }
}

Actually, if MyFun is not a static member of your class, it has a hidden argument that is of type A* , so this is implemented like: m_a.MyFun(...) =~ MyFunImpl(&m_a, ...) . 实际上,如果MyFun不是您的类的静态成员,则它具有类型A*的隐藏参数,因此可以这样实现: m_a.MyFun(...) = MyFunImpl(&m_a, ...)

So, What you want is probably have a static function MyFun (you can't use this inside it), and inside B::Process call f() . 因此,您可能想要的是一个静态函数MyFun (您不能在其中使用this函数),以及在B::Process调用f()

If you need to pass this , refer to casablanca 's answer (pointers to member functions). 如果您需要传递this ,请参考casablanca的答案(指向成员函数的指针)。

Otherwise, if you want to pass an argument, you can lookup std::bind or lambda functions (C++0x), or boost::bind prior to that. 否则,如果要传递参数,则可以在其中查找std::bind或lambda函数(C ++ 0x),或boost::bind

Follow the advice here: http://www.parashift.com/c++-faq-lite/pointers-to-members.html#faq-33.4 , you'll end up with this: 请遵循以下建议: http : //www.parashift.com/c++-faq-lite/pointers-to-members.html#faq-33.4 ,您最终会得到以下结果:

class A;
typedef void (A::*MemFun)();

class B 
{ 
 public: 
 void Process(A& a, MemFun mf) 
 { 
   (a.*mf)(); 
 } 
}; 

class A 
{ 
  public: 
  B m_b; 

  void MyFun() 
  { 
    // do something 
  } 

  void Test() 
  { 
    MemFun p = &A::MyFun;
    A a;
    m_b.Process(a, p); 
  }  
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM