如何在C++的另一个函数中使用局部变量

How to use local variable in another function in C++?

本文关键字:局部变量 函数 另一个 C++      更新时间:2023-10-16

如何在另一个函数中使用局部变量treasureX win?在win函数中,程序使用 board[6][t] 但不使用 treasureX .treasureX变量是全局变量,但代码未按预期工作。

#include <iostream>
#include <random>
#include <ctime>
char board[8][8];
char treasureX;
int t;
void Board() {
    for (int x = 1; x < 7; x++) {
        for (int y = 1; y < 7; y++) {
            board[x][y] = '.';
        }
    }
}

void treasureSpawn() {
    t = rand() % 6 + 1;
    board[6][t] = 'X';
    treasureX = board[6][t];
}
int displayBoard() {
    for (int x = 0; x<8; x++) {
        for (int y = 0; y<8; y++) {
            std::cout << board[x][y];
            if (y == 7) {
                std::cout << std::endl;
            }
        }
    }
    return 0;
}
char playerPosition;
char playerSpawn() {
    int randomY;
    randomY = rand() % 6 + 1; 
    board[1][randomY] = 'G';
    playerPosition = board[1][randomY];
    return playerPosition;
}
int movement() {
    char move;
    std::cout << "Use WASD keys to move." << std::endl;
    std::cin >> move;
    for (int x = 1; x<7; x++) {
        for (int y = 0; y<8; y++) {
            if (board[x][y] == 'G') {
                board[x][y] = '.';
                if (move == 'W' || move == 'w') {
                    return board[x - 1][y] = 'G';
                }
                else if (move == 'A' || move == 'a') {
                    return board[x][y - 1] = 'G';
                }
                else if (move == 'D' || move == 'd') {
                    return board[x][y + 1] = 'G';
                }
                else if (move == 'S' || move == 's') {
                    return board[x + 1][y] = 'G';
                }
                else {
                    std::cout << "Wrong key!" << std::endl;
                    movement();
                }
            }
        }
    }
    return 0;
}
int win() {
    if (treasureX == 'G') { // when player arrives at 'X' this function does not execute. Works if I put 'board[6][t]' instead of 'treasureX'.
        std::cout << "You win" << std::endl;
        return 0;
    }
}
int main() {
    srand(time(0));
    Board();
    playerSpawn();
    outOfBounds();
    treasureSpawn();
    displayBoard();
    do {
        movement();
        checkIf();
        displayBoard();
    } while (win() != 0);
}

将 treasureX 的定义更改为 const char & treasureX = treasureSpawn();,将 treasureSpawn 定义为

const char & treasureSpawn() {
    t = rand() % 6 + 1;
    board[6][t] = 'X';
    return board[6][t];
}

那么当玩家移动到它上面时,treasureX 的值会发生变化

在这里,TreasureX 是一个在函数 void treasureSpawn() 中内化的变量,并且它的值在整个程序中不会改变(并且始终'X'(。但是,board[6][t]在程序执行时会更改,更准确地说是在int movement()函数中,因此当程序执行函数时,它们的值会有所不同win()