Overloading the <<, + and - operators for a matrix

Hello,

I am having some difficulties with an assignment in my Data Structures class that I was hoping someone could help me with.

The assignment is to create a matrix class and overload the <<, addition and subtraction operators.

I am getting the following error messages on the function to overload the + operator and the copy constructor:


"no operator '[]' matches these operands"

and

"C2676 binary '[': 'const matrixType' does not define this operator or a conversion to a type acceptable to the predefined operator"


at the following lines of code:

board[rows][columns] = otherMatrix[rows][columns];

This is the from the copy constructor. The red appears at the first operand for otherMatrix[rows]

and

newMatrix[i][j] = board[i][j] + matrix[i][j];

This is in the function to overload the + operator. The red appears at the first operand for newMatrix[i].


Regarding the second error message, the fix from other forums is to make otherMatrix a pointer not a reference. However, everything else I've found indicates it should be a reference.


This is the constructor for the matrix class:

matrixType::matrixType(int numberOfRows, int numberOfColumns)
{
board = new int * [numberOfRows];
for (int i = 0; i < numberOfRows; i++)
{
board[i] = new int[numberOfColumns];
for (int j = 0; j < numberOfColumns; j++)
{
board[i][j] = rand() % 100;
}
}
}


This is the copy constructor:

matrixType::matrixType(const matrixType& otherMatrix)
{
int rows, columns;

board=new int * [rows];
for (int i=0; i < rows; i++)
{
board[i] = new int[columns];
for (int j = 0; j < columns; j++)
{
board[rows][columns] = otherMatrix[rows][columns];
}
}
}


This is the function to overload the + operator:

matrixType matrixType::operator+(const matrixType&) const
{
int newMatrixRows;
int newMatrixColumns;

matrixType newMatrix(newMatrixRows, newMatrixColumns);

for (int i = 0; i < newMatrixRows; i++)
{
for (int j = 0; j < newMatrixColumns; j++)
{
newMatrix[i][j] = board[i][j] + matrix[i][j];
}
}
return newMatrix;
}


These are the members of the class:

class matrixType
{
public:
matrixType(); //default constructor
matrixType operator+(const matrixType&) const; //function to overload the + operator
matrixType(int numberOfRows, int numberOfColumns); //constructor
matrixType(const matrixType& otherMatrix); //copy constructor
~matrixType(); //destructor


protected:
int **board; //pointer to matrix
friend ostream& operator<<(ostream&, const matrixType& matrix1); //function to overload the << operator
int numberOfRows; //variable for number of rows
int numberOfColumns; //variable for number of columns
};

Any suggestions would be greatly appreciated!

Ragan
otherMatrix.board[K][L]
Topic archived. No new replies allowed.