This is a class with an object 'matrix' that stores a 2D dynamic array. I need to be able to add 2 matrices and put the sum of the elements into the result matrix. (i.e: c[1][1] will equal a[1][1] + b[1][1]). But I want to implement it the following way:
Square_Matrix a,b,c;
c = a + b;
Here are my two overloaded operators, the '=' one works fine outside of '+' (So a = b = c works just fine, matrices get copied over). Unfortunately, I don't get an error on my IDE, the program just closes and says "Square_Matrix has stopped working". How can I fix this?
I'm also not too sure that I implemented my '+' correctly, someone said "return *this" won't do anything.
//.h file
Square_Matrix& operator=(const Square_Matrix& Par2);
Square_Matrix& operator+(const Square_Matrix& Par3);
//.cpp file
Square_Matrix& Square_Matrix::operator=(const Square_Matrix& Par2){
if (size != Par2.size){
cout << "Matrices are of different size" << endl;
} else {
for (int i = 0; i < size; i++){
for (int j = 0; j < size; j++){
matrix[i][j] = Par2.matrix[i][j];
}
}
}
}
Square_Matrix& Square_Matrix::operator +(const Square_Matrix& Par3){
Square_Matrix result;
result.Set_Size(Par3.size);
for (int i = 0; i < Par3.size; i++){
for (int j = 0; j < Par3.size; j++){
result.matrix[i][j] = Par3.matrix[i][j]+matrix[i][j];
}
}
return *this;
}