简体   繁体   中英

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.

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:

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, ...) .

So, What you want is probably have a static function MyFun (you can't use this inside it), and inside B::Process call f() .

If you need to pass this , refer to casablanca 's answer (pointers to member functions).

Otherwise, if you want to pass an argument, you can lookup std::bind or lambda functions (C++0x), or boost::bind prior to that.

Follow the advice here: http://www.parashift.com/c++-faq-lite/pointers-to-members.html#faq-33.4 , you'll end up with this:

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); 
  }  
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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