0

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

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)' fromvoid (*)(unsigned int)'

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

RemoteControlMonitor.H:62:分配给void ()(unsigned int)' fromvoid (*)(unsigned int)'

4

2 回答 2

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);
于 2013-10-28T11:57:49.410 回答
2

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

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

这个链接有一些关于引用、指针和取消引用的方便信息。

希望这可以帮助:)

于 2013-10-28T12:02:08.993 回答