通过运算符重载实现矩阵乘法

Matrix Multiplication through operator overloading

本文关键字:实现 运算符 重载      更新时间:2023-10-16

当我运行它而不是两个矩阵的乘积时,此代码显示地址。

matrix matrix:: operator *(matrix x)
{  
    matrix c(m1,n2);   
    c.m=c.n=m;         
    for(int i=0;i<m1;i++) 
    {        
        for(int j=0;j<n2;j++)        
        {            
            c.a[i][j]=0;           
            for(int k=0;k<n1;k++)
            {
                c.a[i][j]+=(a[i][k]*x.a[k][j]);       
            }   
        } 
    } 
    return c; 
}

对于两个矩阵,可以使用成员一元运算符*=,即:

matrix & operator *= (matrix  const & q)
{
    // ... your code to multiply "this" by q...
    return *this;
}

或非成员二进制运算符:

matrix operator * (matrix p, matrix const & q)
{
    return p *= q;
}