C++实现,洗澡所需条件,并完成洗澡,模拟洗澡过程
时间: 2024-10-24 08:13:51 浏览: 18
在C++编程中,模拟洗澡过程并实现所需的条件,可以创建一个简单的命令式或状态机类来描述这个情景。首先,我们需要定义几个基本的状态(例如:干净、脏污、准备洗澡、正在洗澡、洗完澡),然后编写函数来转换这些状态。
```cpp
class Shower {
public:
enum class State { CLEAN, DIRTY, PREPARING, SHOWERING, DONE };
// 初始化状态
explicit Shower(State initial_state = State::DIRTY)
: state(initial_state) {}
// 模拟动作
void clean() {
if (state == State::DIRTY) {
std::cout << "开始清洗..." << std->state = State::CLEAN;
} else {
std::cout << "身体已经很干净了,不需要再次清洗。";
}
}
void prepare() {
if (state == State::CLEAN || state == State::DIRTY) {
std::cout << "准备进入浴室,打开水龙头..." << std->state = State::PREPARING;
} else {
std::cout << "已经在准备过程中,无需重复。";
}
}
void shower() {
if (state == State::PREPARING) {
std::cout << "开始淋浴..." << std->state = State::SHOWERING;
// 这里可以添加更复杂的流程控制,比如定时器
} else {
std::cout << "已经在洗澡,无需再次启动。";
}
}
void finish() {
if (state == State::SHOWERING) {
std::cout << "冲洗完毕,擦干身体..." << std->state = State::DONE;
} else {
std::cout << "澡已经洗完了。";
}
}
private:
State state; // 保存当前状态
};
int main() {
Shower myShower;
myShower.prepare();
myShower.shower();
myShower.finish();
return 0;
}
```
阅读全文