【问题标题】:How do use a method pointer as a parameter of another method?如何使用方法指针作为另一个方法的参数?
【发布时间】:2015-12-16 00:57:15
【问题描述】:

我已经到处寻找解决方案,可能只是我不知道如何正确地表达它。

我希望这个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 的方法?

【问题讨论】:

  • 你如何想象你可以在没有对象的情况下使用指向成员函数的指针?

标签: c++ function pointers parameters void-pointers


【解决方案1】:

在声明 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)();
}

【讨论】:

    【解决方案2】:

    将代码改为:

    (this->*otherFunction)();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-05-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-14
      • 1970-01-01
      相关资源
      最近更新 更多