C++ 在类中使用typedef定义指向父类函数的函数指针

C++ 在类中使用typedef定义指向父类函数的函数指针,c++,qt,pointers,C++,Qt,Pointers,我尝试将Piconomic HDLC C模块转换为C++类。 我无法将函数指针从Qt程序主窗口类传递到HDLC类。 函数指针可以在HDLC HDLC_init函数中传递,也可以传递给接受这些参数的HDLC HDLC构造函数 假设我们有MainWindow和HDLC类,如何将它们更改为指向 MainWindow::putChar(char data) and MainWindow::onRxFrame(const u8_t *buffer, u16_t bytes_received) cla

我尝试将Piconomic HDLC C模块转换为C++类。

我无法将函数指针从Qt程序主窗口类传递到HDLC类。 函数指针可以在HDLC HDLC_init函数中传递,也可以传递给接受这些参数的HDLC HDLC构造函数

假设我们有MainWindow和HDLC类,如何将它们更改为指向

MainWindow::putChar(char data) and
MainWindow::onRxFrame(const u8_t *buffer, u16_t bytes_received)

class HDLC {
/**
   Definition for a pointer to a function that will be called to 
   send a character
 */
typedef void (*hdlc_put_char_t)(char data);

/**
   Definition for a pointer to a function that will be called once a frame 
   has been received.
 */
typedef void (*hdlc_on_rx_frame_t)(const u8_t *buffer, u16_t bytes_received);
}
void hdlc_init(hdlc_put_char_t    put_char,
                      hdlc_on_rx_frame_t on_rx_frame);
}


// HDLC.cpp:
/// Pointer to the function that will be called to send a character
static hdlc_put_char_t    hdlc_put_char;

/// Pointer to the function that will be called to handle a received HDLC frame
static hdlc_on_rx_frame_t hdlc_on_rx_frame;

void HDLC::hdlc_init(hdlc_put_char_t    put_char,
               hdlc_on_rx_frame_t on_rx_frame)
{
    hdlc_rx_frame_index = 0;
    hdlc_rx_frame_fcs   = HDLC_INITFCS;
    hdlc_rx_char_esc    = FALSE;
    hdlc_put_char       = put_char;
    hdlc_on_rx_frame    = on_rx_frame;
}

HDLC被赋予一个指向MainWindow类函数的指针,这样做是否可行?

您可以将函数类型定义为:

typedef std::function<void(char)> hdlc_put_char_t;

是因为类成员函数指针需要一个调用它们的对象。

非静态成员函数不能转换为正则函数指针。这可能是普通C++程序的一个好选择。但我刚刚意识到,当使用Qt时,通过将所有接收函数转换为SLOT,并将所有外部函数调用转换为发出信号,可以实现相同的最终结果<代码>在接收帧上发射hdlc_(hdlc_接收帧,(quint16)(hdlc_接收帧索引-2))[正确,在Qt信号/插槽机制中优于函数指针。很好,您解决了它:)
MainWindow *mw = new MainWindow;
hdlc.hdlc_init(std::bind(&MainWindow::someFun, mw), ...);