首页 > 解决方案 > C ++将引用传递给同一类中的函数

问题描述

我正在使用 C++ 中的 mbed 框架开发嵌入式系统。要将中断功能附加到串行中断,我通常这样做:

Serial pc(pin_u_tx, pin_u_rx,115200);

void SerialStart(void) {
...
    pc.attach(&SerInt);
...
}

void SerInt(){
    ...
}

但是现在我需要在一个类中做同样的事情,它不起作用,因为我不能引用一个内部函数:

CTCOMM::CTCOMM()
{
    pc = new Serial(ser_tx, ser_rx, ser_baud);
    pc->attach(&serial_interrupt);
}

void CTCOMM::serial_interrupt() {
...
}

我尝试了几种方法,但都没有奏效:

pc->attach(&serial_interrupt);
gives the error
lib\CTcomm\ctcomm.cpp:12:17: error: ISO C++ forbids taking the address of an unqualified or parenthesized non-static member function to form a pointer to member function.  Say '&CTCOMM::serial_interrupt' [-fpermissive]

pc->attach(*serial_interrupt);
gives the error
lib\CTcomm\ctcomm.cpp:12:17: error: invalid use of member function 'void CTCOMM::serial_interrupt()' (did you forget the '

pc->attach(*serial_interrupt());
gives the error
lib\CTcomm\ctcomm.cpp:12:33: error: void value not ignored as it ought to be ()' ?)

pc->attach((*this)->*(serial_interrupt));
gives the error
lib\CTcomm\ctcomm.cpp:12:23: error: invalid use of non-static member function 'void CTCOMM::serial_interrupt()'

等等(我尝试了更多在这里找到的建议,但没有成功)。指向该功能的正确方法是什么?

标签: c++classpointersmbed

解决方案


试试这个。 pc->attach(callback(this, &CTCOMM::serial_interrupt));

pc->attach(this, &CTCOMM::serial_interrupt);也应该工作。但它在 mbed OS 的最新版本中已被弃用。

这是最新的 Mbed API: https ://os.mbed.com/docs/v5.10/mbed-os-api-doxy/classmbed_1_1_serial.html


推荐阅读