给出一个C++状态机案例,可运行
时间: 2024-04-16 14:26:58 浏览: 74
当然,这里有一个简单的C++状态机示,用于模拟一个简单的灯的状态:
```cpp
#include <iostream>
enum class LightState {
Off,
On,
Blinking
};
class Light {
public:
void turnOn() {
currentState = LightState::On;
std::cout << "Light turned on.\n";
}
void turnOff() {
currentState = LightState::Off;
std::cout << "Light turned off.\n";
}
void startBlinking() {
currentState = LightState::Blinking;
std::cout << "Light started blinking.\n";
}
void update() {
switch (currentState) {
case LightState::Off:
// Do nothing
break;
case LightState::On:
// Do nothing
break;
case LightState::Blinking:
std::cout << "Light is blinking.\n";
break;
}
}
private:
LightState currentState = LightState::Off;
};
int main() {
Light light;
light.turnOn();
light.update();
light.startBlinking();
light.update();
light.turnOff();
light.update();
return 0;
}
```
这个例子展示了一个简单的灯状态机,有三种状态:关闭、打开和闪烁。在 `main` 函数中,我们创建了一个 `Light` 对象,并调用不同的方法来改变灯的状态。每次改变状态后,我们调用 `update` 方法来显示当前状态。你可以运行这个例子,它会输出每个状态的相应消息。
阅读全文