我在尝试为矩阵乘法重载乘法运算符 * 时遇到了很多麻烦。我定义了一个矩阵类
#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;
}
我确信元素的实际乘法没有错。
我得到的错误来 self 的主 .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;
}
至于您看到的错误,您似乎在类里面声明运算符采用矩阵并返回 vector 。您可能打算返回一个矩阵。该错误告诉您不能将 MVector
分配给 MMatrix
。
关于C++,为矩阵乘法重载 *,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40635337/