类函数指针作为参数

时间:2012-11-30 19:57:12

标签: c++ function pointers parameters

  

可能重复:
  How to best pass methods into methods of the same class

我从未遇到过将函数指针作为参数传递的问题。这有效:

void functionThatTakesFPTR(void(*function)(int), int someValue){ 
    function(someValue);
   }

void printValue(int value){
    std::printf("%d",value);
}

int main(int argc, char** argv){
    functionThatTakesFPTR(&printValue, 8);

    return EXIT_SUCCESS;
}

但是,传递对象功能不是

void MyClass::setter(float value){ }

void MyClass::testFunction(void(*setterPtr)(float)){ }

void MyClass::someFunc(){
     testFunction(&(this->setter));
}

对我来说,这看起来像是传递了这个地址而不是函数,我有点困惑。有可能这样做吗?是否可以传递另一个类(实例MyClass2)的对象的函数指针?

编辑:我得到的错误是“类'MyClass'没有成员'setter'”。

1 个答案:

答案 0 :(得分:7)

问题是对方法的调用还需要引用类实例。你不能简单地将类方法称为独立函数。

您需要阅读Pointer-to-Member Functions

相关问题