I have two matrices which should multiply together by overloading * operator in the constructor class, but the problem here is that no operator [] matches these operands. Why?
I saw videos and asked my classmates multiple times and tried my own way, but I can't make it work!! I only get this error!!
This is the code I have a problem with:
The Constructor Code:
I made two ways to make this code works. The result should store at cell matrix or the new matrix:
Matrix operator*(const Matrix &matrix1, const Matrix &matrix2)
{
if (matrix1.Cols != matrix2.Rows) {
throw("Error");
}
cell.resize(matrix2.Cols); // one way to call
Matrix res(matrix1.Rows, matrix2.Cols, 1.0); // second way to call
for (int i = 0; i < matrix1.Rows; i++) {
cell[i].resize(matrix1.Rows);
for (int j = 0; j < matrix2.Cols; j++) {
double value_of_elements;
for (int k = 0; k = matrix1.Cols; k++) {
res[i][j] += matrix1[i][k] * matrix2[i][j];//
1. metod
value_of_elements += matrix1[i][k] *
matrix2[i][j];// 2. metod
}
cell[i][j]+=value_of_elements;
}
}
return res;
}
The Header Code:
The header code normally I don't have unless some modification should be made.
friend Matrix operator*(const Matrix &matrix1, const Matrix &matrix2);
The source Code:
This is where the code is tested:
try {
Matrix m1(3, 3, 1.0);
Matrix m2(3, 4, 1.0);
std::cout << "m1*m2:" << m1 * m2 << std::endl;// this si where the matrix should be multiplied here;
}
catch (std::exception &e) {
std::cout << "Exception: " << e.what() << "!" << std::endl;
}
catch (...) {
std::cout << "Unknown exception caught!" << std::endl;
}
system("pause");
return 0;
}
The result:
The result should be this:
m1*m2:[3, 3, 3, 3
3, 3, 3, 3
3, 3, 3, 3]
What I get is an error; the cause of error are that res[i][j], matrix1[i][k] etc. have operators [] wont work on these operands.
Aucun commentaire:
Enregistrer un commentaire