首页 > 解决方案 > 如何更改结构中主函数中的变量?

问题描述

我对 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;
}


标签: c++

解决方案


您需要引用某个结构的对象,而不是 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()


推荐阅读