std::out_of_range 在静态 int 变量上
std::out_of_range on static int variable
我在一个基于 dos 的小型游戏(课程项目(中使用静态变量作为临时计时器。 该变量跟踪状态效果消失之前的圈数。 这是代码:
for (auto &i : v) // <-- code that calls enemyAttack
enemyAttack(i, p, str, i.attack);
break;
void enemyAttack(Enemy &e, playerObject &p, std::array<std::string, NUM_MESSAGES> &str, void(*a)(playerObject &p, std::array<std::string, NUM_MESSAGES> &str)) {
int die = rand() % 100 + 1;
int d = 1;
a(p, str); // <-- Call function which causes the error
...
}
void batAttack(playerObject &p, std::array<std::string, NUM_MESSAGES> &str) {
static int time = 2;
static bool bit = false;
if (rand() % 10 < CHANCE_OF_STATUS_EFFECT && !bit) {
p.damage /= 2;
str[STATUS] += "WEAKENED ";
bit = true;
}
else if (time == 0) {
p.damage *= 2;
str[STATUS].replace(str[STATUS].find("WEAKENED ", 0), 9, "");
time = 2; // <-- error
bit = false;
}
else if (bit) {
time--;
}
}
我在第二个条件内的行time = 2;
收到 std::out_of_range 错误。 此函数通过主攻击函数的函数指针调用。 该错误似乎是随机的,MSVS 报告所有变量在发生错误时具有应有的值。
行
str[STATUS].replace(str[STATUS].find("WEAKENED ", 0), 9, "");
只是一场等待发生的灾难。让我们先看看内在的发现。
str[STATUS].find("WEAKENED ", 0)
当您经常这样做时,您在短程序中使用值"WEAKED"两次,您会遇到拼写错误,因此最好在此处使用命名值,这样就不会出错。
constexpr const char *WeakenedStr = "WEAKENED ";
,然后使用
str[STATUS].find(WeakenedStr , 0)
其次,这可能会失败,如果未找到字符串,它将返回"npos"(当前为 -1(。所以我们也需要测试一下
auto pos = str[STATUS].find("WEAKENED ", 0);
if (pos != std::string::npos)
str[STATUS].replace(pos, 9, "");
接下来是"9",这是一个神奇的数字,也应该是一个命名值
constexpr const char *WeakenedStr = "WEAKENED ";
const int WeakenedStrLen = strlen(WeakenedStr); // strlen is sadly not constexpr.
给
auto pos = str[STATUS].find("WEAKENED ", 0);
if (pos != std::string::npos)
str[STATUS].replace(pos, WeakenedStrLen, "");
注意:未经测试的代码,将出现错误。
相关文章:
- 将布尔变量添加到 int
- 为什么 'main' 函数中的局部 int 变量会自动初始化?
- 在类 (C++) 之外设置 const int 成员变量
- 如何检查 int 变量是否包含合法(非陷阱表示)值?
- 将子字符串字符从字符串值转换为 int,然后将其分配给 int 变量
- 如何在传递给 C/C++ 宏之前解析 int 变量?
- 有什么方法可以使用 int 变量来完成组件名称吗?
- 将 static_cast<int>(-15) 分配给静态常量字符类型变量
- 在C++中,为什么int可以使用new运算符初始化变量,而double不能
- 什么是变量均值'int border = borderType & ~BORDER_ISOLATED'?
- 如何定义int[][26]类型的变量
- 在变量名后声明带有 () 的非内部类型与不使用变量名的行为不同。即 std::map<int,char>x(); - 这是怎么回事?
- 声明具有两种类型的变量:"int char"
- 有没有办法"QByteArray"变量数据直接放入变量"int"而无需强制转换?
- 在 C++ 中,当我声明一个整数变量 int a = 200L 或 int a = 200F 或 int a = 200
- 试图在C++中打印变量int会导致它崩溃.为什么?
- 非常量指针是否可以修改常量变量int c++
- 在初始化中使用新声明的变量(int x=x+1)
- 如何在数组中按变量(int-最小到最大)对数组进行排序
- 如果我想将字符提升为 int,我应该使用 static_cast(char 变量<int>)还是 +(char 变量),为什么?