【问题标题】:Operator overload: Multuplying matrices运算符重载:乘法矩阵
【发布时间】:2017-03-25 13:38:07
【问题描述】:

我正在尝试为矩阵设置一些重载运算符函数,我使用构造函数动态分配它们,并使用 istream 运算符设置值。尝试将两个矩阵相乘时遇到问题(运行时错误)。

任何帮助将不胜感激。 ps:我对模板不熟悉。

这是我的 * 运算符函数:

matrixType operator*(matrixType m)
{
    if( Rows==m.Cols && Cols==m.Rows)
    {
        matrixType m3(Rows,m.Cols);
        for( int i=0; i<Rows;i++)
        {
            for( int j=0; j<Cols; j++)
            {
                {
                  for(int g=0; g<Cols;g++)
                      m3.matrix[i][j]+=matrix[i][g] * m.matrix[g][j];
                }
            }
        }
        return m3;
    }
}

这是我的复制操作符函数:

matrixType& operator=( matrixType& m)
{
    for (int i =0; i<Rows; i++)
    {
         for ( int j=0; j<Cols; j++)
                matrix[i][j]=m.matrix[i][j];
    }

    return *this;
}

【问题讨论】:

标签: c++ matrix operator-overloading


【解决方案1】:

我认为最好在运行代码时发布一些运行时错误。无论如何,我在您的乘法运算符函数中发现了一个问题:

当你返回m3时,它是在另一个作用域中定义的,所以它没有被定义,你把return m3语句放在if作用域内怎么样:

matrixType operator*(matrixType m)
{
    if( Rows==m.Cols && Cols==m.Rows)
    {
        matrixType m3(Rows,m.Cols);
        for( int i=0; i<Rows;i++)
        {
            for( int j=0; j<Cols; j++){
                    {for(int g=0; g<Cols;g++)
                    m3.matrix[i][j]+=matrix[i][g] * m.matrix[g][j];}
        }
        return m3;
    }
      // Throw some error if your assertion is not satisfied, perhaps
    }
}

【讨论】:

    【解决方案2】:

    您在 j 循环中使用了错误的 Cols。你想要m.Cols 那里:

    for (for( int j=0; j<m.Cols; j++)
    

    查看 ijg 变量用于下标的位置,以了解 3 个循环的限制值。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-03-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-29
      • 1970-01-01
      相关资源
      最近更新 更多