使用Arduino虚拟方法

Using virtual methods with Arduino

本文关键字:方法 虚拟 Arduino 使用      更新时间:2023-10-16

我有一小段Arduino代码,给我编译错误:

error: no matching function for call to 'PushButton::PushButton(int, LeftButtonEvent*) 

在它自己的头文件中有两个类:

class Event
{
public:
    virtual void handle() {
    }
};
class PushButton
{
public:
    PushButton(int pinButton, Event *event);
    uint8_t read();
private:
    uint8_t _buttonState;
    Event _event;
};

和类的源文件:

PushButton::PushButton(int pinButton, Event *event)
{
    // implementation
}
uint8_t PushButton::read() {
    // implementation
    return _buttonState;
}

在main/sketch头文件中,我定义了一个扩展Event类的新类:

class LeftButtonEvent : public Event {
public:
    virtual void handle();
};

在草图源文件中,我提供了handle方法的实现并使用它:

void LeftButtonEvent::handle() {
    log("Is working!!!!!");
}
LeftButtonEvent leftButtonEvent;
PushButton leftButton;
void setup()   {    
    leftButton = PushButton(PIN_LEFT_BUTTON, &leftButtonEvent);
}

我期望PushButton的构造函数接受LeftButtonEvent类型,因为它扩展了Event类,但看起来它不喜欢它。我错过什么了吗?

因为只有不完整的代码,我不能直接测试它,有一个例子如何让它工作(它都在一个草图,Arduino IDE 1.6.12, c++ 11):

class Event {
  public:
    virtual void handle() = 0;
};
class EventLeft : public Event {
  public:
    virtual void handle() {
      Serial.println("EventLeft");
    }
} leftEvent;
class EventRight : public Event {
  public:
    virtual void handle() {
      Serial.println("EventRight");
    }
} rightEvent;
class PushButton {
  public:
    PushButton(int8_t _pin, Event * _event) : pin(_pin), state(true), event(_event) {
      pinMode(pin, INPUT_PULLUP);
    }
    void check() {
      if (! digitalRead(pin)) { // inverted logic
        if (state) event->handle();
        state = false;
      } else {
        state = true;
      }
    }
  private:
    int8_t    pin;
    bool    state;
    Event * event;
};
PushButton buttons[] = {
  {4, &leftEvent},
  {5, &rightEvent}
};
void setup()   {    
  Serial.begin(115200);
}
void loop() {
  delay(10);
  for (PushButton & button : buttons) button.check();
  //// if the range based for loop above doesn't work, you have to use old school one:
  // for (uint8_t i = 0; i < 2; ++i) buttons[i].check();
}