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

aja*_*ari 15 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;
}
Run Code Online (Sandbox Code Playgroud)

我尝试编译时遇到以下错误.

error C2276: '&' : illegal operation on bound member function expression
Run Code Online (Sandbox Code Playgroud)

Snp*_*nps 19

你不能将函数指针强制转换为void*.

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

ReturnType (ClassType::*)(ParameterTypes...)
Run Code Online (Sandbox Code Playgroud)

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

func_ptr p = &t1.get_pc // Error
Run Code Online (Sandbox Code Playgroud)

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

func_ptr p = &test::get_pc // Ok, using class scope.
Run Code Online (Sandbox Code Playgroud)

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

(this->*cb_func)(); // Call function via pointer to current instance.
Run Code Online (Sandbox Code Playgroud)

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

#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();
}
Run Code Online (Sandbox Code Playgroud)

  • void test :: call_cb_func(){(this - >*cb_func)(); 一个人永远不想通过指针内的对象来调用函数.因此,示例中的"this"是完全无用的解释.鉴于C++是除十六进制之外可能最不人道的语法,人们不能简单地猜测如何从另一个对象调用该函数. (2认同)

Att*_*que 5

除了 Snps 的答案之外,您还可以使用C++11 中的函数包装器来存储 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();
}
Run Code Online (Sandbox Code Playgroud)