将指向类成员函数的指针作为参数传递

时间:2013-08-09 11:41:09

标签: c++ function-pointers

我编写了一个小程序,我试图将指向类的成员函数的指针传递给另一个函数。你能帮助我和我出错的地方吗??

#include<iostream>
using namespace std;
class test{
public:
        typedef void (*callback_func_ptr)();
        callback_func_ptr cb_func;

        void get_pc();

        void set_cb_ptr(void * ptr);

        void call_cb_func();
};
void test::get_pc(){
         cout << "PC" << endl;
}
void test::set_cb_ptr( void *ptr){
        cb_func = (test::callback_func_ptr)ptr;
}
void test::call_cb_func(){
           cb_func();
}
int main(){
        test t1;
            t1.set_cb_ptr((void *)(&t1.get_pc));
        return 0;
}

当我尝试编译它时出现以下错误。

error C2276: '&' : illegal operation on bound member function expression

2 个答案:

答案 0 :(得分:19)

您无法将函数指针强制转换为void*

如果希望函数指针指向成员函数,则必须将类型声明为

ReturnType (ClassType::*)(ParameterTypes...)

此外,您不能声明指向绑定成员函数的函数指针,例如

func_ptr p = &t1.get_pc // Error

相反,你必须得到这样的地址:

func_ptr p = &test::get_pc // Ok, using class scope.

最后,当您调用指向成员函数的函数指针时,必须使用该函数所属的类的实例来调用它。例如:

(this->*cb_func)(); // Call function via pointer to current instance.

以下是应用了所有更改的完整示例:

#include <iostream>

class test {
public:
    typedef void (test::*callback_func_ptr)();
    callback_func_ptr cb_func;
    void get_pc();
    void set_cb_ptr(callback_func_ptr ptr);
    void call_cb_func();
};

void test::get_pc() {
    std::cout << "PC" << std::endl;
}

void test::set_cb_ptr(callback_func_ptr ptr) {
    cb_func = ptr;
}

void test::call_cb_func() {
    (this->*cb_func)();
}

int main() {
    test t1;
    t1.set_cb_ptr(&test::get_pc);
    t1.call_cb_func();
}

答案 1 :(得分:2)

除了Snps的答案,您还可以使用C ++ 11中的function wrapper来存储lambda函数:

#include <iostream>
#include <functional>

class test
{
  public:
   std::function<void ()> Func;
   void get_pc();
   void call_cb_func();
   void set_func(std::function<void ()> func);
};

void test::get_pc()
{
  std::cout << "PC" << std::endl;
}

void test::call_cb_func()
{
  Func();
}

void test::set_func(std::function<void ()> func)
{
  Func = func;
}

int main() {
  test t1;
  t1.set_func([&](){ t1.get_pc(); });
  t1.call_cb_func();
}
相关问题