c++ - 如何更改结构中主函数中的变量?
问题描述
我对 C++ 和一般的编码很陌生,而且我似乎永远被这个错误所困扰。
我的最终目标是创建一个井字游戏算法,但目前我在使用结构体之外的结构体变量时遇到了问题。
我尝试过使用类和结构,使用静态等,我知道我错过了一些我只是不知道它是什么的东西。
这是代码,它不是很漂亮,但我很确定它应该可以工作。
#include <iostream>
#include <string>
int userResponse;
//Class to monitor board positions
struct boardPos
{
bool Pos1 = 0;
bool Pos2 = 0;
bool Pos3 = 0;
bool Pos4 = 0;
bool Pos5 = 0;
bool Pos6 = 0;
bool Pos7 = 0;
bool Pos8 = 0;
bool Pos9 = 0;
};
//Changing bool values
void boolChange()
{
if (userResponse == 1)
{
boardPos::Pos1 = 1;
}
if (userResponse == 2)
{
boardPos::Pos2 = 1;
}
if (userResponse == 3)
{
boardPos::Pos3 = 1;
}
if (userResponse == 4)
{
boardPos::Pos4 = 1;
}
}
//std::string A, B, C, D, E, F, G, H, I
int main()
{
//Variable to Print Position Board
std::string posBoard = "\n 1 | 2 | 3\n-----------\n 4 | 5 | 6\n-----------\n 7 | 8 | 9\n";
std::cout << posBoard;
std::cout << "Enter Position Number\n";
std::cin >> userResponse;
}
解决方案
您需要引用某个结构的对象,而不是 sturct 本身。
void boolChange(boardPos &b)
{
if (userResponse == 1)
{
b.Pos1= 1;
}
if (userResponse == 2)
{
b.Pos2 = 1;
}
if (userResponse == 3)
{
b.Pos3 = 1;
}
if (userResponse == 4)
{
b.Pos4 = 1;
}
}
请注意,函数定义已更改,现在它引用了boardPos
. 现在您需要创建一个对象,boardPos
然后通过引用将其传递给boolChange()
推荐阅读
- ansible - 使用 with_items 和 vmware_guest for vSphere 访问 Ansible 清单变量
- json - 如何将json文本写入excel,但仍然显示json格式?
- python - 如何通过 conda 在 databricks 中安装库(cfgrib)?
- swift - 强大而廉价的数组算法
- c# - 使用 Delta 查询获取用户不会返回带有 C# 代码的 nextLink 或 deltaLink
- java - 如何在运行时更改属性值而不在 Spring MVC 中重新启动应用程序服务器
- wordpress - Wordpress Gutenberg 构建器订阅表单块在页脚小部件上不起作用?
- android - 有时在 android kotlin 上的同一键上处理对象/数组的动态响应
- javascript - 当 Selector 找到更多匹配元素时强制测试失败
- python - 如何区分条件语句的浮点数和整数(经过一些计算)?