【发布时间】:2018-01-29 00:33:53
【问题描述】:
我在一个基于 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 报告的所有变量都具有错误发生时应具有的值。
【问题讨论】:
-
什么是
STATUS?NUM_MESSAGES是什么?他们的价值观是什么?请尝试创建Minimal, Complete, and Verifiable Example 并展示给我们。 -
另外,如果
str[STATUS].find("WEAKENED ", 0)没有找到您要查找的字符串,您认为会发生什么?即使某些事情本应“永远不会发生”,但它总是会发生! -
您不会碰巧有多个线程同时尝试访问此静态变量吗?
-
这是一个编程入门课程的课程项目,我们还没有讨论线程。 STATUS 是枚举的一部分,NUM_MESSAGES 是一个 const int,其值是枚举中 STATUS 所属的值的数量。
标签: c++ c++11 variables static int