【发布时间】:2016-11-16 14:59:58
【问题描述】:
我在尝试重载乘法运算符 * 以进行矩阵乘法时遇到了很多麻烦。我已经定义了一个矩阵类
#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”)
【问题讨论】:
-
MVector operator*(const MMatrix& A);什么是 MVector? -
您在类中声明了一个成员
operator*重载,它返回一个MVector,但随后定义了一个全局operator*重载,它返回一个MMatrix。选择一种返回类型,然后选择是要实现类成员还是全局函数。 -
好的,MVector 正在为我的矩阵向量乘法返回一个向量,但它工作正常。我现在已经把 MMatrix MMatrix::operator*(const MMatrix & A) 放在课堂上,虽然我不确定我现在如何进行乘法