2015-11-13 48 views
0

所以我正在爲我的AI類製作一個類似於C++ Checkers的遊戲。我遇到了一陣呃逆,這讓我瘋狂,每個對手的棋子都是一個包含方向的結構:bool left;布爾權利;當我嘗試改變其中一個值爲真時,它似乎沒有改變。這似乎是一個範圍問題,但我不知道爲什麼,我已經通過使用vs調試工具來跟蹤它。下面是一些代碼:更改方法C++中的結構變量

 typedef struct { 
     int pos; 
     int num; 
     bool left; 
     bool right; 
    }opp; 
    int scoreOp(opp o){ 

     if (scoreMoveOp(o.pos + 7) == 10){ 
      o.left = true; 
      return 10; 
     } 
     else if (scoreMoveOp(o.pos + 9) == 10){ 
      o.right = true; 

      return 10; 
     } 

    int scoreOp(opp o){ 

     if (scoreMoveOp(o.pos + 7) == 10){ //scoreMoveOp essentially returns ten. 
      o.left = true; 
      return 10; 
     } 
     else if (scoreMoveOp(o.pos + 9) == 10){ 
      o.right = true; 

      return 10; 
     } 

,是所有被稱爲:

void checkOPPListForX(){ 
     for (int i = 0; i < O1Moves.size(); i++){ 
      if (X == O1Moves[i].second){ 
       //cout << "O1 has it, and its score is: " << scoreOp(O1) << endl; 
       O1Score = scoreOp(O1); 
       O1Check = true; 
      } 
      else O1Check = false; 
     } 

    checkOPPListForX(); 
      if (O1Score > O2Score && O1Score > O3Score && O1Score > O4Score){ 
       //move O1; 
       //O1.pos 
       if (O1.left) 
        O1.pos = O1.pos + 7; 
       else if (O1.right) 
        O1.pos = O1.pos + 9; 
      } 
+0

您可能正在複製副本,實際上(錯誤地)希望訪問唯一實例。 –

回答

2

你的價值,這意味着該函數獲取副本傳遞變量到scoreOp功能。修改副本當然不會修改原始內容。

您需要通過參考而不是傳遞參數

int scoreOp(opp& o){ ... } 
//   ^
//    | 
// Note ampersand here, which means that the argument is passed by reference 
0

最簡單的方法是把你的功能結構裏面:

typedef struct { 
    int pos; 
    int num; 
    bool left; 
    bool right; 
    int scoreOp() {.....} 
}opp; 

,然後你可以用OPP叫它.ScoreOp()

此解決方案是如果你不太舒服,通過參考