将指向类成员函数的指针作为参数传递 [英] Passing a pointer to a class member function as a parameter

查看:2718
本文介绍了将指向类成员函数的指针作为参数传递的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了一个小程序,我试图传递一个类的成员函数的指针到另一个函数。你能帮助我和我错了吗?

I have written a small program where I am trying to pass a pointer to member function of a class to another function. Can you please help me and where I am going wrong..?

#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;
}

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

I get the following error when I try to compile it.

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


推荐答案

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

You cannot cast a function pointer to void*.

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

If you want a function pointer to point to a member function you must declare the type as

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

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

Further you cannot declare a function pointer to a bound member function, e.g.

func_ptr p = &t1.get_pc // Error

而您必须取得如下地址:

Instead you must get the address like this:

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

最后,当调用指向成员函数的函数指针时,与该函数是其成员的类的实例。例如:

Finally, when you make a call to a function pointer pointing to a member function, you must call it with an instance of the class that the function is a member of. For instance:

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






下面是应用所有更改的完整示例: / p>


Here's the full example with all changes applied:

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

这篇关于将指向类成员函数的指针作为参数传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆