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

标签 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

最佳答案

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

如果你想要一个函数指针指向一个成员函数你必须声明类型为

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

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

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

关于c++ - 将指向类成员函数的指针作为参数传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18145874/

相关文章:

c++ - 如何针对 "suspicious sizeof"或 SIZEOF_MISMATCH 结果训练 Coverity?

c++ - 根据模板参数选择合适的复制构造函数

c++ - std::pair 作为模板<class> 参数? C++

c# - 如何将 C# 函数指针传递给 CLI/C++ 代码?

c++ - vector 删除多个区域,2次删除与单次分配?

c++ - 了解语言环境类,locale::facet::_S_create_c_locale 名称无效

c - C 中的自动函数指针

c - 将 foo(int *) 作为参数传递给 X 中的 foo(void*)

go - 如何在最新的 Go 周刊中比较两个函数的指针相等性?

c - 分配作为参数传入的函数指针