2015-11-13 47 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()

此解决方案是如果你不太舒服,通过参考