C++写一个简单的状态机实现

在C++中实现一个事件驱动的状态机,您可以在StateMachine类中添加事件枚举和处理事件的方法。以下是一个简单的事件驱动状态机示例:

#include 

// 定义状态枚举
enum class State {
    Idle,
    Running,
    Paused,
    Stopped
};

// 定义事件枚举
enum class Event {
    Start,
    Pause,
    Resume,
    Stop
};

class StateMachine {
private:
    State currentState;

public:
    StateMachine() : currentState(State::Idle) {}

    void handleEvent(Event event) {
        switch (event) {
            case Event::Start:
                start();
                break;
            case Event::Pause:
                pause();
                break;
            case Event::Resume:
                resume();
                break;
            case Event::Stop:
                stop();
                break;
        }
    }

private:
    void start() {
        if (currentState == State::Idle || currentState == State::Stopped) {
            currentState = State::Running;
            std::cout << "状态已更改为:运行中" << std::endl;
        } else {
            std::cout << "无法启动:状态机已进行中或处于暂停状态" << std::endl;
        }
    }

    void pause() {
        if (currentState == State::Running) {
            currentState = State::Paused;
            std::cout << "状态已更改为:暂停" << std::endl;
        } else {
            std::cout << "无法暂停:状态机未运行" << std::endl;
        }
    }

    void resume() {
        if (currentState == State::Paused) {
            currentState = State::Running;
            std::cout << "状态已更改为:运行中" << std::endl;
        } else {
            std::cout << "无法恢复:状态机未暂停" << std::endl;
        }
    }

    void stop() {
        if (currentState == State::Running || currentState == State::Paused) {
            currentState = State::Stopped;
            std::cout << "状态已更改为:停止" << std::endl;
        } else {
            std::cout << "无法停止:状态机未运行或暂停" << std::endl;
        }
    }

public:
    State getState() const {
        return currentState;
    }
};

int main() {
    StateMachine stateMachine;

    stateMachine.handleEvent(Event::Start);
    stateMachine.handleEvent(Event::Pause);
    stateMachine.handleEvent(Event::Resume);
    stateMachine.handleEvent(Event::Stop);

    return 0;
}

在这个示例中,我们添加了一个名为Event的枚举以表示可能的事件。我们还为StateMachine类添加了一个handleEvent方法,该方法接收一个Event参数并根据事件类型调用相应的函数(如start、pause等)。现在,在main函数中,您可以通过调用stateMachine.handleEvent并传递相应的事件来测试状态跳转。 

你可能感兴趣的:(自动驾驶,c++,开发语言,java)