C++ 通过引用传递不改变值

C++ pass by reference not changing value

下面是用于分析井字棋盘的函数的第一部分。

aboutToWin() 函数 returns 如果玩家 "about to win," 为真,即连续两个。棋盘表示为如果玩家 1 在该方块中移动,则 3x3 矩阵中的值将为 1。玩家 2 将为 -1。如果没有人出手,则为0。

我在这个问题中的部分是第一部分,它检查负对角线(即棋盘上的位置 1、5 和 9)。

bool aboutToWin(int squares[3][3], int& position, bool p1)
{
    // The value you are looking for is 2 for p1 and -2 for p2
    int check = 2;
    if (!p1)
    {
        check = -2;
    }

    // Check negative diagonal
    int sum = 0;
    // Go through negative diagonal
    for (int i = 0; i < 3; i++)
    {
        sum += squares[i][i];
        // Saves the position of the last checked 0 square
        // If check passes, this will be the winning square
        // If not, it will get handled and overwritten
        if (squares[i][i] == 0)
        {
            // Calculates position from i
            position = 1 + (4 * i);
            std::cout << "\nPosition: " << position << "\n";
        }
    }

    // If this diagonal added to check, stop the function and return now
    if (sum == check)
        return true;

    ...
}

这是我 运行 来自 main() 函数的代码,用于测试此功能:

int p;
std::cout << p;

int a3[3][3] = {{1, 0, 1},
                {0, 0, 0},
                {0, 0, 1}}; 

std::cout << "\nShould be 1, 5: " << aboutToWin(a3, p, true) << ", " << p;

输出如下:

0
位置:5

应该是 true, 5: 1, 0

这是为什么?我可以看到值在函数执行过程中发生了变化,但它并没有传出函数。

使用问题:

std::cout << "\nShould be 1, 5: " << aboutToWin(a3, p, true) << ", " << p;

除非使用 C++17,否则参数的计算顺序未定义。

看起来 p 在调用 aboutToWin 之前首先在您的设置中进行评估。

分开通话。

auto ret = aboutToWin(a3, p, true);
std::cout << "\nShould be 1, 5: " << ret << ", " << p;