如何在C++的另一个函数中使用局部变量
How to use local variable in another function in C++?
如何在另一个函数中使用局部变量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()
相关文章:
- 局部变量保留函数中的值
- 如何使用 C++ 中的继承函数访问派生类中的局部变量
- 如何在函数外部访问函数中局部变量的值?
- 赋予全局变量而不是局部变量优先级的函数 - (异常行为)
- 获取具有静态局部变量的绑定/推断捕获 lambda 的函数指针
- 是否可以影响 C++ 中回调函数的局部变量?
- 将共享指针传递给函数参数 - 将其分配给局部变量的正确方法是什么
- 调用一个小函数两次(例如在if条件和主体中)比将结果存储在局部变量中更可取
- C++ - 指向函数中局部变量的指针
- 如何在 C++ 的 lambda 函数中传递同名的局部变量和参数(使用此关键字)?
- Clang++ 6.0 内存清理器未报告返回值指示条件分支的函数中的未初始化局部变量
- 如何将局部变量传递给 lambda 函数
- 局部变量的作用域是块或函数
- 函数原型未初始化的局部变量
- 尝试声明函数的局部变量,但得到范围错误
- 如果对象是通过 new 创建的,则成员函数的局部变量在哪里创建?
- 如果两个线程调用同一个函数,但函数中的所有变量都是局部变量,我还需要担心线程之间共享数据吗?
- 如果函数抛出的异常可能未捕获,如何销毁局部变量?
- 为什么不能在模板函数中向局部变量添加低级 const 类型
- 使用clang_complete自动完成局部变量/函数