'incompatible types in assignment' when passing custom function type [duplicate]

半城伤御伤魂 提交于 2019-12-24 21:10:34

问题


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:

incompatible types in assignment of 'void (**)(uint8_t*) {aka void (**)(unsigned char*)}' to 'void (* [0])(uint8_t*) {aka void (* [0])(unsigned char*)}'

The only difference being * vs a [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 trimmed down

#include "Comms.h"


Comms::Comms(bool isMaster, uint16_t hz, DataHandler handlers[]){
  master = isMaster;
  pingDelay = 1/hz;
  dataHandlers = handlers; ######ERROR HERE######

  ////setup code////
  ...

回答1:


You have two options here:

  1. You can label dataHandlers/handlers/both as a DataHandler *.
  2. You can label the aforementioned variables as an std::vector<DataHandler>, with handlers being an lvalue (std::vector<DataHandler> &) reference.

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.



来源:https://stackoverflow.com/questions/48676953/incompatible-types-in-assignment-when-passing-custom-function-type

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!