【发布时间】:2013-03-09 12:33:18
【问题描述】:
这是一个 Arduino 项目,它有一个模式按钮。该按钮将当前应用程序变量更改为播放器/收音机/导航/电话。所有的应用程序都继承自“App”。
如果我运行“apps[0]->volume_up();”,它会告诉我应用程序中没有方法 volume_up。如果我将它添加到 App 中,它会在 App 中而不是在 Player 中执行 volume_up。
我做错了什么?
int index = 0;
App *apps[4];
void setup(){
Player *player = new Player();
Radio *radio = new Radio();
Navigation *navigation = new Navigation();
Phone *phone = new Phone();
apps[0] = player;
apps[1] = radio;
apps[2] = navigation;
apps[3] = phone;
}
void loop(){
int sensorValue = analogRead(A0);
if (sensorValue == 156 || sensorValue == 157){ // Mode button
index = (index + 1) % (sizeof(apps)/sizeof(apps[0]));
delay(300);
}
if (sensorValue == 24 || sensorValue == 23){ // Volume button
apps[index]->volume_up();
delay(100);
}
}
编辑
#ifndef App_H
#define App_H
#include "Arduino.h"
class App {
public:
void volume_up();
};
#endif
#include "App.h"
void App::volume_up(){
Serial.println("VOLUME_UP");
}
【问题讨论】:
-
请看一下虚方法,你应该在
App中定义一个,然后在子类中覆盖它。请参考polymorphism。 -
重新标记为
C++。C中没有虚方法。App是如何定义的? -
我用应用类更新了问题