When I try to use this line in main.cpp:
m3.array = m1.array+m2.array;
where m3, m1, and m2 are all objects of a class type Matrix, with an int[3][3] array –
I keep getting an error that deals with an incompatible assignment of type int[3][3] and int[3][3] to opperand ‘+’. I don’t know the exact error, because I’m not at a computer to compile the program.
Here’s the matrix.cpp I have:
#include <iostream>
#include <string>
#include "matrix.h"
using namespace std;
Matrix::Matrix()
{
m1.array = 0;
}
istream& opeator >>(istream& inp, Matrix& m1)
{
int i, j;
for (i = 0; i < 3;i++)
{
for (j=0; j < 3;j++)
{
inp >> m1.array[i][j];
}
}
return inp;
}
ostream& operator <<(istream& outp, Matrix& m1)
{
int i, j;
for (i = 0;i<3;i++)
{
for (j = 0;j<3;j++)
{
out<<m1.array[i][j]<<" "<<endl;
}
}
return outp;
}
Matrix operator + (const Matrix& m1, const Matrix& m2)
{
Matrix answer;
int i,j;
for (i = 0;i<3;i++)
{
for (j = 0;j<3;j++)
{
answer.array[i][j] = m1.array[i][j] + m2.array[i][j];
}
}
return answer;
}
Matrix operator - (const Matrix& m1, const Matrix& m2)
{
Matrix answer;
int i, j;
for (i = 0;i<3;i++)
{
for (j = 0;j<3;j++)
{
answer.array[i][j] = m1.array[i][j] - m2.array[i][j];
}
}
return answer;
}
Matrix operator * (const Matrix& m1, const matrix& m2)
{
Matrix answer;
int i, j, k;
for (i = 0;i<3;i++)
{
for (j = 0; j<3;j++)
{
for (k = 0; k<3;k++)
{
answer.array[i][j] = m1.array[i][k] + m2.array[k][j];
}
}
}
return answer;
}
and the matrix.h:
#ifndef MATRIX_H
#define MATRIX_H
using namespace std;
class Matrix
{
public:
Matrix();
friend istream& operator >>(istream&, Matrix&);
friend ostream& operator <<(ostream&, const Matrix&);
friend Matrix& operator +(const Matrix&, const Matrix&);
friend Matrix& operator -(const Matrix&, const Matrix&);
friend Matrix& operator *(const Matrix&, const Matrix&);
int array[3][3];
};
#endif
This tells the computer how to add two
Matrixobjects, good job.m1andm2areMatrixobjects, butm1.arrayis not. That is aint[3][3]object. Luckily, the fix is very very simple: