如何将一个方法指针用作另一个方法的参数

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

本文关键字:方法 指针 另一个 参数 一个      更新时间:2023-10-16

我到处都在寻找解决方案,可能只是我不知道如何正确地用语言表达。

我希望这个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)();
}