I am attempting to make a board object for a tic tac toe game, and can’t get around this error.
class Board {
public:
void reset() {
board[3][3] = {
{" ", " ", " "},
{" ", " ", " "},
{" ", " ", " "}
};
};
private:
std::string board[3][3];
Board() {
reset();
};
};
I’ve tried switching the variable type from std::string to char but it throws a different error which makes no sense either
>Solution :
I think you may have an issue with your reset() method of the Board class. It’s trying to change the value of the board member variable (of type String[][]) using the = operator which is not possible because arrays are not assignable in C++.
There are two fixes that I see for this issue:
the fix I would use (if you want to keep the same vibe of your code) is to loop over every value in the board and set the strings individually to " " like this:
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
board[i][j] = " ";
}
}
changing the class to look like this:
class Board {
public:
void reset() {
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
board[i][j] = " ";
}
}
};
private:
std::string board[3][3];
Board() {
reset();
};
};
However, if you are looking for something more modern, I’d recommend the C++ std::array instead of a raw array. Utilizing the std::array would give you access to the built-in fill() method (i.e. std::array::fill) to initialize the array as follows:
#include <array>
#include <string>
class Board {
public:
void reset() {
board.fill(" ");
};
private:
std::array<std::array<std::string, 3>, 3> board;
Board() {
reset();
};
};