如何从他们自己的类的成员函数中访问公共变量? (C ++)

时间:2017-12-21 02:05:30

标签: c++ class scope

我想从我的一个成员函数中访问我在类开头声明的公共变量。但是它说它超出了范围。

Goban :: Goban(构造函数)效果很好。它成功访问并更改了" board"和" isWhiteToPlay",按预期。

printBoard的代码在调用此类的程序中有效,但是现在我已将它移到此处,编译的尝试遇到了"'board'未被声明在这个范围内"。在playMove中,无论是董事会还是白手都没有逃脱同样的命运。

我在这里做错了什么?它是一个公共变量,但它不应该是因为我还在课堂上,对吗?有没有一种简单的方法可以从Goban的功能中访问和修改Goban的变量?我不希望将board作为指针处理,以便将它传递给函数然后返回它。我想我能做到,但我无法想象那里的方式并不是那么优雅。

class Goban
    {
    public:
      int board[9][9]; // y,x  -1 = W  +1 = B
      int captures[2];
      bool isWhiteToPlay; // 0 for Black's turn, 1 for White's turn

  Goban();
  void printBoard(); // Prints the board to the terminal wherefrom the program is called.
  void playMove(int x, int y); // Makes a move for the turn player at the coordinate (x,y). Right now I'm just trying to get it to change the value of the proper coordinate of "board" and not caring if the move is legal.
};

Goban::Goban() // Just initializing everything to zero here for now. Interesting to note that there are no compiling errors in this constructor. But later it complains when I use board and isWhiteToPlay elsewhere. The only difference I can see is that here they're in for loops, and there they're in if clauses. Not sure why that would make a difference, nor how to work around it.
{
  captures[0] = 0;
  captures[1] = 0;

  for (int j = 0; j <= 8; j++)
  {
    for (int i = 0; i <=8; i++)
    {
      board[j][i] = 0;
    }
  }

  isWhiteToPlay = 0;
}

void printBoard() // This code worked correctly when it was in the program, but the problem started when I moved it here to the class.
{
  for (int j = 0; j <= 8; j++)
  {
    for (int i = 0; i <= 8; i++)
    {
      if (board[j][i] == -1)
        { std::cout << " O"; }
      else if (board[j][i] == 1)
        { std::cout << " X"; }
      else
        { std::cout << " ."; }
    }
  }
}

void playMove(int x, int y) // Same errors as above; solution is probably the same.
{
  if (isWhiteToPlay == 0)
  {
    board[y][x] = -1;
    isWhiteToPlay = 1;
  }
  else
  {
    board[y][x] = 1;
    isWhiteToPlay = 0;
  }
}

我怀疑有人可能已经问过这个问题了,但我想我还没有提出正确的搜索条件,这可能表明我并不完全理解我所做的事情。我在这里做错了。如果有人理解这个问题我已经足够了解正确的搜索条件,那么欢迎链接到相应的现有stackoverflow线程。当然,我不会在这里抱怨答案,但不需要重新发明轮子,以及所有这些。

1 个答案:

答案 0 :(得分:2)

您的意思是拥有Goban::printBoardGoban::playMove。实际上,你只是声明+定义自由函数。

e.g。

void Goban::printBoard() 
{
}

就像你的构造函数一样:

Goban::Goban()
{
}

我假设你说

  

printBoard的代码在调用此类的程序中起作用

您的意思是,当您在类声明中使用代码时,它曾经工作过,但您现在已将它们移动到单独的定义中。