使用Arduino虚拟方法
Using virtual methods with Arduino
我有一小段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();
}
相关文章:
- 用常见虚拟函数实现的任意组合来实现派生类的正确方法是什么
- 在模板基类中为继承类中的可选重写生成虚拟方法
- 跨 DLL 边界访问虚拟方法是否安全/可能?
- 是否可以使用基类非虚拟方法中的派生类虚拟方法?
- 如何编写 operator= 用于使用虚拟方法与非平凡成员的匿名联合
- 让编译器告诉什么确切的纯虚拟方法使结构抽象?
- 使用模板而不是虚拟方法的管道模式
- 派生类调用父类的方法,该方法调用重写的虚拟方法调用错误的方法
- 从纯虚拟类 (A) 派生的指针无法访问来自纯类 (B) 的重载方法
- 为什么调用没有正文的纯虚拟方法不会导致链接器错误?
- 出于什么目的,非虚拟方法将与C++一起使用?
- 为什么使用存储在虚拟方法表中的地址调用虚拟函数的函数会返回垃圾?
- 如何重写继承的嵌套类中存在的虚拟方法
- 私有虚拟方法有什么用?
- 派生类中纯虚拟基方法的专业化
- 基类可以声明虚拟方法但不定义它吗?仍然在派生类中定义
- googletest:测试基类具有纯虚拟方法的派生类时的核心转储
- 确保模拟的 GTest 方法覆盖虚拟方法
- 使用回调函数从构造函数调用虚拟/派生方法的替代方法?
- 如何调用孩子的方法:虚拟关键字不起作用