Как я могу умножить матрицы, перегрузив оператор *, если оператор не соответствует операндам? - PullRequest
0 голосов
/ 01 мая 2019

У меня есть две матрицы, которые должны умножаться вместе с помощью оператора перегрузки * в классе конструктора, но проблема здесь в том, что никакие operator [] не соответствуют этим операндам.Зачем?

Я видел видео, несколько раз спрашивал своих одноклассников и пытался по-своему, но я не могу заставить его работать.Я получаю только эту ошибку!

Вот код, с которым у меня проблема:

Код конструктора:

Я сделал два способа заставить этот код работать.Результат должен храниться в ячейке матрицы или новой матрице:

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;
   }

Код заголовка:

Код заголовка обычно у меня нет, если только не будут внесены какие-либо изменения.

friend Matrix operator*(const Matrix &matrix1, const Matrix &matrix2);

Исходный код:

Здесь проверяется код:

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;
}

Результат:

Результат должен быть таким:

m1*m2:[3, 3, 3, 3
3, 3, 3, 3
3, 3, 3, 3]

Я получаю сообщение об ошибке;причина ошибки в том, что res[i][j], matrix1[i][k] и т. д. имеют операторы [], которые не будут работать с этими операндами:

Error   C2065   'cell': undeclared identifier 71  matrix.cpp
Error   C2065   'cell': undeclared identifier 74  matrix.cpp
Error   C2065   'cell': undeclared identifier 81  matrix.cpp
Error   C2088   '[': illegal for class 79   matrix.cpp 
Error   C2088   '[': illegal for class 78   matrix.cpp  
Error   C2676   binary '[': 'Matrix' does not define this operator or a conversion to a type acceptable to the predefined operator  78  matrix.cpp
Error   C2676   binary '[': 'const Matrix' does not define this operator or a conversion to a type acceptable to the predefined operator    78  matrix.cpp
Error   C2676   binary '[': 'const Matrix' does not define this operator or a conversion to a type acceptable to the predefined operator    79  matrix.cpp
Error (active)  E0020   identifier "cell" is undefined  71  Matrix.cpp
Error (active)  E0349   no operator "[]" matches these operands 78  Matrix.cpp
Error (active)  E0349   no operator "[]" matches these operands 78  Matrix.cpp
Error (active)  E0349   no operator "[]" matches these operands 78  Matrix.cpp
Error (active)  E0349   no operator "[]" matches these operands 79  Matrix.cpp
Error (active)  E0349   no operator "[]" matches these operands 79  Matrix.cpp  

Ответы [ 2 ]

0 голосов
/ 01 мая 2019

Получил мой ответ здесь:

Matrix operator*(const Matrix &matrix1, const Matrix &matrix2)
{
    if (matrix1.Cols != matrix2.Rows) {
        throw("Error");
    }
    Matrix res(matrix1.Rows, matrix2.Cols, 0.0);
    for (int i = 0; i < matrix1.Rows; i++) {
        for (int j = 0; j < matrix2.Cols; j++) {
            double value_of_elements;
            for (int k = 0; k < matrix1.Cols; k++) {
                res.cell[i][j] += matrix1.cell[i][k] * matrix2.cell[i][j];
            }
        }
    }
    return res;
}
0 голосов
/ 01 мая 2019

Предполагая, что матрица классов имеет член vector<vector<double>> cell, вот пример, который умножает матрицы:

Matrix operator*(const Matrix &matrix1, const Matrix &matrix2)
  {
    if (matrix1.Cols != matrix2.Rows) {
        throw("Error");
    }
    Matrix res(matrix1.Rows, matrix2.Cols, 1.0);
    for (int i = 0; i < matrix1.Rows; i++) {
        for (int j = 0; j < matrix2.Cols; j++) {
            double value_of_elements=0;
            for (int k = 0; k = matrix1.Cols; k++)
                value_of_elements += matrix1.cell[i][k] * matrix2.cell[k][j];
            res.cell[i][j]=value_of_elements;
        }
    }
    return res;
}

Было три проблемы.Во-первых, у класса Matrix нет оператора [].Проблема была решена путем прямого доступа к члену cell.Во-вторых, переменная value_of_elements не была инициализирована, поэтому результат не определен.В-третьих, умножение матриц не было сделано правильно.Вы умножаете один столбец из matrix1 на один столбец из matrix2, тогда как вы должны умножать строку на столбец.

...