2017-08-21 67 views
0

我在一個小型的基於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報告所有變量具有發生錯誤時應該具有的值。

+0

什麼是'STATUS'?什麼是'NUM_MESSAGES'?他們的價值是什麼?請嘗試創建[最小,**完整**和可驗證示例](http://stackoverflow.com/help/mcve)並向我們顯示。 –

+0

另外,如果'str [STATUS] .find(「WEAKENED」,0)'沒有找到你要找的字符串,你會怎麼想呢?即使某些東西本該「永遠不會發生」,它總是會! –

+0

你不會偶然有多個線程會嘗試訪問這個靜態變量在同一時間嗎? – 9Breaker

回答

0

str[STATUS].replace(str[STATUS].find("WEAKENED ", 0), 9, ""); 

只是等待發生的災難。先看看內部的發現。使用值

str[STATUS].find("WEAKENED ", 0) 

你在執行此操作時往往不夠,你將有拼寫錯誤的短節目「周小平」的兩倍,因此它能夠更好地所以沒有犯錯誤的機會,在這裏使用了一個名爲值。

constexpr const char *WeakenedStr = "WEAKENED "; 

然後用

str[STATUS].find(WeakenedStr , 0) 

其次,這可能會失敗,如果字符串沒有找到返回「非營利組織」(這是目前-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, ""); 

注意:未經測試的代碼,將發生錯誤。

+0

它工作了!謝謝!我距離到期日只有兩天,並開始擔心。 – user2200783