问题描述
我正在创建一个类来处理两个无线电之间的一些无线电通信,每个无线电都连接到一个 Arduino.我计划将一个函数列表传递给类来处理收到的不同消息.
I am creating a class to handle some radio-communication between two radios each connected to an Arduino. I was planning on having a list of functions passed to the class to handle different messages that are received.
我的问题是,将函数数组保存到私有变量后,出现以下错误:
My problem is that upon saving an array of functions to a private variable I get the following error:
'void (**)(uint8_t*) {aka void (**)(unsigned char*)}' to 'void (* [0])(uint8_t*) {akavoid (* [0])(unsigned char*)}'
唯一的区别是 *
与 [0]
Comms.h
class Comms {
public:
//data handlers are arrays of functions that handle data received with an id equal to their index in the array
typedef void (*DataHandler)(uint8_t data[RH_RF95_MAX_MESSAGE_LEN]);
Comms(bool isMaster, uint16_t Hz, DataHandler handlers[]);
void updateRun();
//first element should be the id, followed by some data
void queueData(uint8_t data[RH_RF95_MAX_MESSAGE_LEN]);
int8_t getLastRSSI();
private:
RH_RF95 *rf95;
QueueList<uint8_t[]> messageQueue;
bool master;
uint16_t pingDelay;
DataHandler dataHandlers[];
};
Comms.cpp 已精简
#include "Comms.h"
Comms::Comms(bool isMaster, uint16_t hz, DataHandler handlers[]){
master = isMaster;
pingDelay = 1/hz;
dataHandlers = handlers; ######ERROR HERE######
////setup code////
...
推荐答案
这里有两个选择:
- 您可以将
dataHandlers
/handlers
/both 标记为DataHandler *
. - 您可以将上述变量标记为
std::vector
,处理程序是左值 (std::vector &
) 引用.
- You can label
dataHandlers
/handlers
/both as aDataHandler *
. - You can label the aforementioned variables as an
std::vector<DataHandler>
, with handlers being an lvalue (std::vector<DataHandler> &
) reference.
我在重新创建代码的关键方面时遇到的错误是堆栈分配的数组基本上是不可变的指针,因此您基本上编写了与 DataHandler * const
等效的内容.由于所有字段都有默认初始化,无论您是否在构造函数的初始化列表中指定一个(您不能为 dataHandlers 的类型,因为您实际上在字段声明中指定了它的默认值),您本质上是试图重新分配您的 DataHandler 指针所指向的内容.
The error I encountered when recreating the key aspect of your code was that stack-allocated arrays are basically immutable pointers, so you were basically writing the equivalent of DataHandler * const
. Since all fields have a default initialization, whether or not you specified one in the initializer list in your constructor (you can't for the type you have for dataHandlers, as you essentially specified its default value in the field declaration), you were essentially attempting to reassign what your DataHandler pointer was pointing to.
这篇关于传递自定义函数类型时“分配中的类型不兼容"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!