指向同一类(C ++)中的成员函数的指针?

时间:2012-11-03 21:37:38

标签: c++ class pointers

我正在编写一个程序来控制Arduino Mega微控制器上的汽车家庭酿造系统(用C / C ++编写)。简而言之,程序正在做的是有一个C#应用程序,它定期通过USB向微控制器发送消息。然后我写了一个消息接口,它读取消息,并将其转发给消息所用的任何组件。每条消息长16个字节,前4个是事务代码,最后12个是数据。现在,我在消息中读到并转发到我的StateController类。它来自InboundMessage函数。我想要做的是我有一个struct(在StateController.h中定义),它包含事务代码和StateController中成员函数的指针。我定义了一个QueueList(只是一个简单的链表库),并将一堆这些结构推入其中。我想要做的是当一条消息进入inboundMessage函数时,我想循环遍历链表,直到找到匹配的事务代码,然后调用该消息的成员函数,传递给它消息中的数据。

我认为我已经正确初始化了所有内容,但这是问题所在。当我尝试编译时,我得到一个错误,说“在这个范围内不存在func”。我已经到处寻找解决方案,但找不到一个。我的代码在

之下
StateController.cpp

StateController::StateController(){
  currentState = Idle;
  prevState = Idle;
  lastRunState = Idle;

  txnTable.push((txnRow){MSG_BURN, &StateController::BURNprocessor});
  txnTable.push((txnRow){MSG_MANE, &StateController::MANEprocessor});
  txnTable.push((txnRow){MSG_MAND, &StateController::MANDprocessor});
  txnTable.push((txnRow){MSG_PUMP, &StateController::PUMPprocessor});
  txnTable.push((txnRow){MSG_STAT, &StateController::STATprocessor});  
  txnTable.push((txnRow){MSG_SYNC, &StateController::SYNCprocessor});
  txnTable.push((txnRow){MSG_VALV, &StateController::VALVprocessor});
}

void StateController::inboundMessage(GenericMessage msg){
  // Read transaction code and do what needs to be done for it

  for (int x = 0; x < txnTable.count(); x++)
  {
    if (compareCharArr(msg.code, txnTable[x].code, TXN_CODE_LEN) == true)
    {
      (txnTable[x].*func)(msg.data);
      break;
    }
  }
}

StateController.h

class StateController{
  // Public functions
  public:

    // Constructor
    StateController();

    // State Controller message handeler
    void inboundMessage(GenericMessage msg);

    // Main state machine
    void doWork();

  // Private Members
  private:  

    // Hardware interface
    HardwareInterface hardwareIntf;

    // Current state holder
    StateControllerStates currentState;

    // Preveous State
    StateControllerStates prevState;

    // Last run state
    StateControllerStates lastRunState;

    // BURN Message Processor
    void BURNprocessor(char data[]);

    // MANE Message Processor
    void MANEprocessor(char data[]);

    // MAND Message Processor
    void MANDprocessor(char data[]);

    // PUMP Message Processor
    void PUMPprocessor(char data[]);

    //STAT Message Processor
    void STATprocessor(char data[]);

    // SYNC Message Processor
    void SYNCprocessor(char data[]);

    // VALV Message Processor
    void VALVprocessor(char data[]);

    void primePumps();

    // Check the value of two sensors given the window
    int checkSensorWindow(int newSensor, int prevSensor, int window);

    struct txnRow{
    char code[TXN_CODE_LEN + 1];
    void (StateController::*func)(char[]);
    };

    QueueList<txnRow> txnTable;

};

知道出了什么问题吗?

1 个答案:

答案 0 :(得分:1)

func只是txnRow的正常成员,因此您可以使用.访问它,而不是.*,例如txnTable[x].functhis

要在(this->*(txnTable[x].func))(msg.data); 上调用此成员函数,您可以执行以下操作:

{{1}}