c++ - 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()'
等等(我尝试了更多在这里找到的建议,但没有成功)。指向该功能的正确方法是什么?
解决方案
试试这个。
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
推荐阅读
- java - 通过 CDI 在单元测试中检索替代 entityManager
- plot - 在 Dymola 图中标记 X 和 Y 轴
- r - 使用 pmfa 函数时,R (SensoMineR) 未生成所有图
- python - subprocess.Popen() 不执行命令?
- shell - Keycloak Gatekeeper 未正确设置 X-Auth 标头
- jquery - 卡片大小因图像高度而不同?
- fonts - `rmarkdown`/`bookdown` 中的自定义字体:保留 **bold**/*italic*、特殊字体功能(`--`)等?
- java - 将我的 Android 客户端与 Java 应用服务器连接的最佳方式是什么?
- c++ - QSqlError("", "参数计数不匹配", "") 关于qt
- c - 使用指针反转字符串