如何使用方法指针作为另一个方法的参数?

How do use a method pointer as a parameter of another method?

我找遍了这个问题的解决方案,可能只是我不知道如何正确地表达它。

我希望这个 firstFunctionfirstFunction 的参数中声明其地址时调用 otherFunction

这是我的代码:

init.h:

class Ainit
{
  //function to be passed into firstFunction
  void test();
  void firstFunction( void (Ainit::*otherFunction)() );  
};

init.cpp:

void Ainit::firstFunction( void (Ainit::*otherFunction)() )
{
    (Ainit::*otherFunction)();
}

Xcode:指向以下行中的 * 并出现错误:Expected unqualified-id

(Ainit::*otherFunction)();

如何在 firstFunction 中调用传递给 firstFunction 的方法?

将代码更改为:

(this->*otherFunction)();

声明firstFunction的参数和调用*otherFunction时不需要Ainit::。下面的代码就可以了:

class Ainit { 

void test();

void firstFunction (void * otherFunction());
};

void Ainit::test() {
std::cout << "Hello" << std::endl;
}

void Ainit::firstFunction(void * otherFunction()) {
(*otherFunction)();
}