自增变量"never used"?

Incremented variable "never used"?

我对 C++ 不太熟悉,我正在将我用 C 编写的程序转换为 C++。我有一个 RollDice 函数,它获取我从文本文件中读入的数字并使用它们生成数字。这是C:

中的函数
void rollDice(Move *move, GameState *game_state) {
    int diceNum1 = 0;
    int diceNum2 = 0;
    int randomNumber1 = 0;
    int randomNumber2 = 0;
    randomNumber1 = game_state->randomNums[game_state->current_roll]; //gets the random number from the array randomNum (which holds the numbers from the text file), at index "current_roll"
    game_state->current_roll++; //increments so the next random number will be the next number in the array
    diceNum1 = 1 + (randomNumber1 % (1 + 6 - 1));
    randomNumber2 = game_state->randomNums[game_state->current_roll];
    game_state->current_roll++;
    diceNum2 = 1 + (randomNumber2 % (1 + 6 - 1));
    move->dice_sum = diceNum1 + diceNum2;
    printf("You rolled a %d!\n", move->dice_sum);
}

当我 运行 它时,这正是我想要的。现在,在将我的程序转换为 C++ 时,我不得不改变一些东西。我的参数现在通过引用传递,我制作了一个向量来存储文本文件中的随机数列表:

void rollDice(Move& move, GameState& game_state) {
    std:: vector<int> randomNums = game_state.getRandomNums();
    int current_roll = game_state.getCurrentRoll();
    int diceNum1 = 0;
    int diceNum2 = 0;
    int randomNumber1 = 0;
    int randomNumber2 = 0;
    randomNumber1 = randomNums.at(current_roll);
    current_roll++;
    diceNum1 = 1 + (randomNumber1 % (1 + 6 - 1));
    randomNumber2 = randomNums.at(current_roll);
    current_roll++;   //this line is grayed out and says "this value is never used"
    diceNum2 = 1 + (randomNumber2 % (1 + 6 - 1));
    move.dice_sum = diceNum1 + diceNum2;
    std:: cout << "You rolled a " << move.dice_sum << "!\n";
}

我的代码告诉我,我第二次递增 current_roll 它未被使用。我的 C 代码没有发生这种情况,那么为什么会发生在这里,我该如何解决呢?我完全迷路了。

它从未被使用,因为您写入变量,但从未从中读取。拥有一个您从未阅读过的变量实际上毫无意义。

大概你的 game_state.getCurrentRoll 函数 returns 一个整数,当你存储这个时,你存储 value (而不是对值的引用),因此,增加它不会增加 game_state 内的当前滚动,相反,您应该向 game_state 添加一个名为 makeRoll 的函数,例如增加 game_states 内部 current_roll值。

这与您的 C 代码不同,后者使用 game_state->current_roll++ 直接 递增 current_roll(或者您可以使 game_state.current_roll public 并以与 C 代码中相同的方式增加它。

根据你的评论,我假设你有一些 class:

class GameState {
private:
    int current_roll;
    ...
public:
    int getCurrentRoll() {
        return current_roll;
    }
    ...
}

您需要做的就是向 class 添加另一个函数来增加 current_roll:

class GameState {
private:
    int current_roll;
    ...
public:
    int getCurrentRoll() {
        return current_roll;
    }
    void makeRoll() {
        current_roll++;
    }
    ...
}

然后就可以正常调用了


关于错误评论中的新问题:

parameter type mismatch: Using 'unsigned long' for signed values of type 'int'.

这是因为 at 的签名是 std::vector::at( size_type pos ); 也就是说,它期望 size_type 类型的值是无符号整数类型,而不是 int正如您正在使用的那样,它已签名。 This post 可能会有帮助。