我在一個小型的基於dos的遊戲(課程項目)中使用靜態變量作爲轉換計時器。變量記錄了狀態效果消失之前的轉數。下面是代碼:std :: out_of_range on static int變量
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--;
}
}
我接收一個std :: out_of_range誤差在第二條件內的線time = 2;
。該功能通過主要攻擊函數的函數指針調用。錯誤似乎是隨機的,MSVS報告所有變量具有發生錯誤時應該具有的值。
什麼是'STATUS'?什麼是'NUM_MESSAGES'?他們的價值是什麼?請嘗試創建[最小,**完整**和可驗證示例](http://stackoverflow.com/help/mcve)並向我們顯示。 –
另外,如果'str [STATUS] .find(「WEAKENED」,0)'沒有找到你要找的字符串,你會怎麼想呢?即使某些東西本該「永遠不會發生」,它總是會! –
你不會偶然有多個線程會嘗試訪問這個靜態變量在同一時間嗎? – 9Breaker