繁体   English   中英

C ++,重载*用于矩阵乘法

[英]C++, overload * for matrix multiplication

我在尝试重载乘法运算符*进行矩阵乘法时遇到了很多麻烦。 我已经定义了一个矩阵类

#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

这是我尝试的运算符重载

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。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM