因此,我正在为我的AI类制作一个类似C++跳棋的游戏。我遇到了一个让我发疯的小问题,每个对手的棋子都是一个包含方向的结构:布尔左;布尔右;当我尝试将其中一个值更改为真时,它似乎没有改变。这似乎是一个范围问题,但我不知道为什么,我一直在使用vs调试工具跟踪它。下面是一些代码:
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;
}发布于 2015-11-14 03:27:18
通过值将变量传递给scoreOp函数,这意味着该函数将获得一个副本。当然,修改副本并不会修改原件。
您需要通过引用传递参数:
int scoreOp(opp& o){ ... }
// ^
// |
// Note ampersand here, which means that the argument is passed by reference发布于 2015-11-14 03:29:05
最简单的方法是将您的函数放在struct中:
typedef struct {
int pos;
int num;
bool left;
bool right;
int scoreOp() {.....}
}opp;然后您可以使用opp.ScoreOp()调用它
这个解决方案是如果您不太习惯通过引用传递的话
https://stackoverflow.com/questions/33700318
复制相似问题