如何使用函数名作为参数?

时间:2013-10-28 11:52:27

标签: c++ function parameters

我尝试将函数名称作为参数传递如下:

class RemoteControlMonitor {
private:
    void (*rph)(unsigned int key);
    void (*rrh)(unsigned int key);

public:
    RemoteControlMonitor(void (*pressed)(unsigned int key), 
                     void (*released)(unsigned int key) = 0) {
     *rph = pressed;
     *rrh = released;
     lr_set_handler(remote_control_handler);
    }

    void runPressed() {
     while (!shutdown_requested()) {
         remote_key = 0;
         remote_etype = 0;
         wait_event(&remote_control_pressed, 0);

             if (*rph) {
                 (*rph)(remote_key);
             }
         }
     }
 };

编译时,错误如下,我该怎么办?

RemoteControlMonitor.H:在方法`RemoteControlMonitor :: RemoteControlMonitor(void()(unsigned int),void()(unsigned int)= 0)':

RemoteControlMonitor.H:61:分配只读位置

RemoteControlMonitor.H:61:赋值给void ()(unsigned int)' from void(*)(unsigned int)'

RemoteControlMonitor.H:62:分配只读位置

RemoteControlMonitor.H:62:赋值给void ()(unsigned int)' from void(*)(unsigned int)'

2 个答案:

答案 0 :(得分:2)

尝试使用typedef会更清楚。

typedef  void (*keyaction)(unsigned int key);

class RemoteControlMonitor {
private:
    keyaction rph;
    keyaction rrh;

public:
    RemoteControlMonitor(keyaction pressed, 
                     keyaction released = NULL) {
     rph = pressed;
     rrh = released;
     lr_set_handler(remote_control_handler);
    }

    void runPressed() {
     while (!shutdown_requested()) {
         remote_key = 0;
         remote_etype = 0;
         wait_event(&remote_control_pressed, 0);

             if (rph) {
                 (*rph)(remote_key);
             }
         }
     }
 };

修改

此函数转到构造函数:

void f(unsigned int){}

你声明如下:

RemoteControlMonitor  rcm(f);

答案 1 :(得分:2)

你不需要取消引用你的指针,*rph,只需像rph一样正常调用它,它应该可以正常工作,否则你试图将指针*rph设置为压制而不是它的价值。

*rph = pressed表示将我的记忆位置设为pressed,其中rph = pressed表示将我的值设为pressed

This链接有关于引用,指针和解除引用的一些方便信息。

希望这会有所帮助:)