C++;将引用传递给同一类内的函数 我正在开发一个用C++中的MBOD框架的嵌入式系统。 要将中断功能附加到串行中断,我通常会执行以下操作: Serial pc(pin_u_tx, pin_u_rx,115200); void SerialStart(void) { ... pc.attach(&SerInt); ... } void SerInt(){ ... }
但现在我需要在类内部做同样的事情,但它不起作用,因为我不能引用内部函数:C++;将引用传递给同一类内的函数 我正在开发一个用C++中的MBOD框架的嵌入式系统。 要将中断功能附加到串行中断,我通常会执行以下操作: Serial pc(pin_u_tx, pin_u_rx,115200); void SerialStart(void) { ... pc.attach(&SerInt); ... } void SerInt(){ ... },c++,class,pointers,mbed,C++,Class,Pointers,Mbed,但现在我需要在类内部做同样的事情,但它不起作用,因为我不能引用内部函数: CTCOMM::CTCOMM() { pc = new Serial(ser_tx, ser_rx, ser_baud); pc->attach(&serial_interrupt); } void CTCOMM::serial_interrupt() { ... } 我尝试了几种方法,但没有一种有效: pc->attach(&serial_interrupt); gives
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()'
等等(我尝试了这里找到的更多建议,但没有成功)。
指向该函数的正确方法是什么?试试这个。
pc->attach(回调(这个,&CTCOMM::串行中断))代码>
pc->attach(此,&CTCOMM::串行中断)代码>也应该起作用。但在最新版本的mbed操作系统中,它已被弃用
以下是最新的Mbed API:
我认为您在这里没有选择,因为您需要一个指向函数的指针。唯一的方法是使用静态方法。attach
的签名是什么?您是否可以将其修改为使用,例如,std::invoke
来调用回调函数?然后您可以将这个作为调用成员函数的第一个参数,类似于附加(&CTCOMM::serial\u interrupt,this)
。搜索“指向成员函数的指针”第一个给出了此错误:lib\CTcomm\CTcomm.cpp:13:56:错误:无法在参数传递中将“CTcomm*”转换为“unsigned char*”
,但第二个有效,只是警告已弃用!我会尝试修复第一个,但现在谢谢,它可以工作了。