重载*矩阵乘法

C++, overload * for matrix multiplication

本文关键字:重载      更新时间:2023-10-16

我在尝试重载矩阵乘法运算符*时遇到了很大的麻烦。我定义了一个矩阵类

#ifndef MMATRIX_H
#define MMATRIX_H
#include <vector>
#include <cmath>
// Class that represents a mathematical matrix
class MMatrix
{
public:
// constructors
MMatrix() : nRows(0), nCols(0) {}
MMatrix(int n, int m, double x = 0) : nRows(n), nCols(m), A(n * m, x)
{}
// set all matrix entries equal to a double
MMatrix &operator=(double x)
{
    for (int i = 0; i < nRows * nCols; i++) 
        A[i] = x;
return *this;
}
// access element, indexed by (row, column) [rvalue]
double operator()(int i, int j) const
{
    return A[j + i * nCols];
}
// access element, indexed by (row, column) [lvalue]
double &operator()(int i, int j)
{
    return A[j + i * nCols];
}

// size of matrix
int Rows() const { return nRows; }
int Cols() const { return nCols; }
// operator overload for matrix * vector. Definition (prototype) of member class
MVector operator*(const MMatrix& A);
private:
unsigned int nRows, nCols;
std::vector<double> A;
};
#endif

这是我尝试的operator overload

inline MMatrix operator*(const MMatrix& A, const MMatrix& B)
{
MMatrix m(A), c(m.Rows(),m.Cols(),0.0);
for (int i=0; i<m.Rows(); i++)
{
    for (int j=0; j<m.Cols(); j++)
    {
        for (int k=0; k<m.Cols(); k++)
        {
            c(i,j)+=m(i,k)*B(k,j);
        }
    }
}
return c;
}

我确信实际的元素乘法没有任何问题。

我得到的错误是从我的主。cpp文件中,我试图将两个矩阵相乘在一起C=A*B;我得到这个错误,

错误:没有匹配'operator='(操作数类型为'MMatrix'和'MVector')

有两种方法重载operator*:

MMatrix MMatrix::operator*(MMatrix); //or const& or whatever you like
MMatrix operator*(MMatrix, MMatrix);

它们都是有效的,但在语义上略有不同。

为使定义与声明匹配,将定义更改为:

MMatrix MMatrix::operator*(const MMatrix & A)
{
    //The two matrices to multiple are (*this) and A
    MMatrix c(Rows(),A.Cols(),0.0);
    for (int i=0; i < Rows(); i++)
    {
        for (int j=0; j < A.Cols(); j++)
        {
            for (int k=0; k < Cols(); k++)
            {
                c(i,j) += (*this)(i,k)*A(k,j);
            }
        }
    }
    return c;
}

对于您看到的错误,似乎在您的类中声明了操作符以获取矩阵并返回向量。你可能想要返回一个矩阵。

错误是告诉你不能将MVector分配给MMatrix

我认为,您需要定义复制构造函数和复制赋值:

MMatrix(const MMatrix& other);
MMatrix& operator=(const MMatrix& other);

移动构造函数和赋值也不会动:

MMatrix(MMatrix&& other);
MMatrix& operator=(MMatrix&& other);

MVector也是一样