Hello,
I'm trying to make a simple tic-tac-toe game and am having trouble with using 'friend'. During the computer's move I want the computer's class to access and modify the board array in the 'Gameboard' class.
I have declared the 'Computer' class a 'friend' in the 'Gameboard' header. However on compile a number of errors occur:
In computer cpp:
1 2 3 4 5
line 27 'board' was not declared in this scope
line 28 invalid use of member (did you forget the '&'?)
line 35 'board' has not been declared
line 35 Prototype for'bool Computer::validateMove(int, char, char, int)' does not match any class in computer
line 41'board' was not declared in this scope
I've spent ages renaming and rearranging code but I'm guessing that there's a fundamental concept I'm missing. Any help would be great thanks.
line 27: when you make class A a friend of class B, A can access private members of B object. You do need to have a B class object. board is a member of GameBoard class. You cannot access it without a GameBoard object. The right way would be my_board.board. You could either make boardObj a global variable (not suggested) or add a GameBoard& to Computer class.
line 28: validateMove is a function, not a variable. The right way would be }while(validateMove(/*some arguments*/) == false);
line 35: when you put something in argument list you must specify its class (GameBoard in this case)
line 35: since compiler couldn't understand your arguments it cannot find appropriate function declared in Computer class and complains about it.
line 41: this is caused by errors on line 35. I can't say what is the compiler thinking though..
Thanks for the reply... your suggestion fixed the 'validateMove' problem...
I'm still unsure on the 'friend' problem...
I've changed a few functions and tried to use the boardObj as an argument in the compMove function.
In 'main' I changed boardObj.makeMove(comp.compMove(x,o), compPiece);
to boardObj.makeMove(comp.compMove(x,o,boardObj), compPiece);
I now only get the following error on lines 7 and 8 in the Computer cpp code that follows: No matching function for call to 'Computer::validateMove(char&,char&, char&, char[3][3])'
This is because function expects Gameboard object, you give it Gameboard::board which is char[3][3]. Just change 'boardSet.board' to 'boardSet' since you want to pass the whole object and not only its member.
Nore: line 7 is useless. You're just calling the same function twice..