1

Okay, so essentially I have a struct of a piece on a board, as follows:

struct piece
{
    int value;
    bool revealed;
    bool canMove(int x, int y)
    {
        //This is where the problem is.
        if (board[x][y].value == 13) //If it's not occupied
            return true;
        else
            return false;
    }
};

//Define the board
piece board[x][y];

And it's giving me errors such as 'board': undeclared identifier. How can I fix this? I've tried putting the board declaration before the struct, but then it just says that piece is an undeclared identifier.

I realize I could just pass in the board as a parameter, but I have several functions, and that would take a lot more time than I would like, so if there is any other solution, please tell me!

This question is related (but not identical) to Question

Community
  • 1
  • 1
JFed-9
  • 297
  • 3
  • 17

3 Answers3

2

You have to decouple the class definition from the implementation of its member functions, so that the compiler always knows what you're talking about:

struct piece
{
    int value;
    bool revealed;
    bool canMove(int x, int y);  // this is sufficient for the moment
};

piece board[x][y];   // now, compiler knows what a piece is. 

bool piece::canMove(int x, int y) 
{                    // now board is known as well
    if (board[x][y].value == 13) 
        return true;
    else
        return false;
}
Christophe
  • 68,716
  • 7
  • 72
  • 138
1

Declare canMove inside the class, then define it outside after you have declared board. At that point you can successfully refer to board.

Alan Stokes
  • 18,815
  • 3
  • 45
  • 64
1

You are mixing piece with pieces. This is really wrong design.

Your method canMove belongs to single piece. So its definition should rdflect this fact:

bool canMove() const
{
  return value == 13;
}

To get what you want to get from 2D array of pieces - just do:

board[x][y].canMove()

Of course you can creare new class Board to encapsulate its behaviour,like methods canMove with 2 arguments.

PiotrNycz
  • 23,099
  • 7
  • 66
  • 112
  • Well the canMove function returns a boolean depending on the values inside the array of its member struct. The position on the board and the pieces surrounding the piece in question all come together to define whether the piece can move. I just simplified the function to make it easier to understand. – JFed-9 May 08 '16 at 22:33
  • Since I have already created the entire program, and the problem was relatively small, I'd rather not edit 500 lines of code when I can just decouple it like the previous answers suggested. – JFed-9 May 08 '16 at 22:35
  • If the project is in its after-development phase - then of course - you do not need to change. But if it will be maintained, new features added, then this "design smell" will cost you more and more - and in such case - changing it now would be the best option. – PiotrNycz May 09 '16 at 07:46