#include <iostream>
#include <string>
class Game {
public:
// 定义枚举类型GameStatus
enum class GameStatus {
INITIALIZED,
IN_PROGRESS,
PAUSED,
ENDED
};
// 根据GameStatus执行不同逻辑的成员函数
void executeLogic(GameStatus status) {
switch (status) {
case GameStatus::INITIALIZED:
std::cout << "游戏已初始化,准备开始。" << std::endl;
break;
case GameStatus::IN_PROGRESS:
std::cout << "游戏正在进行中。" << std::endl;
break;
case GameStatus::PAUSED:
std::cout << "游戏已暂停。" << std::endl;
break;
case GameStatus::ENDED:
std::cout << "游戏已结束。" << std::endl;
break;
}
}
// 自定义类型转换
static std::string toString(GameStatus status) {
switch (status) {
case GameStatus::INITIALIZED:
return "INITIALIZED";
case GameStatus::IN_PROGRESS:
return "IN_PROGRESS";
case GameStatus::PAUSED:
return "PAUSED";
case GameStatus::ENDED:
return "ENDED";
}
return "";
}
static GameStatus fromString(const std::string& str) {
if (str == "INITIALIZED") {
return GameStatus::INITIALIZED;
} else if (str == "IN_PROGRESS") {
return GameStatus::IN_PROGRESS;
} else if (str == "PAUSED") {
return GameStatus::PAUSED;
} else if (str == "ENDED") {
return GameStatus::ENDED;
}
return GameStatus::INITIALIZED;
}
};
- 枚举类型定义:在
Game
类中使用enum class
定义了GameStatus
枚举类型,它包含了游戏的不同状态。
- 执行逻辑的成员函数:
executeLogic
函数根据传入的GameStatus
值,通过switch - case
语句执行不同的逻辑。
- 自定义类型转换:
- 转换为字符串:
toString
静态函数将GameStatus
枚举值转换为对应的字符串表示。
- 从字符串转换:
fromString
静态函数将字符串转换为对应的GameStatus
枚举值。如果字符串不匹配任何已知值,返回默认值GameStatus::INITIALIZED
。