【问题标题】:c++ matrix overloading not workingc ++矩阵重载不起作用
【发布时间】:2015-11-29 07:40:11
【问题描述】:

无法弄清楚发生了什么。 为什么运算符重载在此代码中不起作用?

class matrix
{
protected:

    int matrix1[5][5],matrix2[5][5],resultmatrix[5][5];
    int m,n,p,q,i,j,k,l;
    public: matrix()
        {
        }
        void getdata();
        //double determinat;
        matrix operator  +(matrix);
        void showmatrix();
};

    void matrix::getdata()
    {
    cout<<"\n"<<"enter no of rows for matrix1 : "<<"\n";
    cin>>m;
    cout<<"\n"<<"enter no of columns for matrix1 : "<<"\n";
    cin>>n;
    cout<<"\n"<<"enter no of rows for matrix2 : "<<"\n";
    cin>>p;
    cout<<"\n"<<"enter no of columns for matrix2 : "<<"\n";
    cin>>q;

    if(m==p&&n==q)
    {
        cout<<"\n"<<"matrixes can be added"<<"\n";
    }
    else
    {
    cout<<"\n"<<"matrixes can not be added"<<"\n";
    exit(0);
    }

    cout<<'\n'<<"please provide for matrix1: "<<"\n";

    for( i=0;i<m;i++)
    {
        for(j=0;j<n;j++)
        {
            cin>>matrix1[i][j];
        }
    }

    cout<<'\n'<<"please provide for matrix2: "<<"\n";

    for(int i=0;i<m;i++)
    {
        for(int j=0;j<n;j++)
        {
            cin>>matrix2[i][j];
        }
    }

  }

    matrix matrix::operator+( matrix matrixobj)

{ 矩阵 tempmatrixobj;

for(i=0;i<m;i++)
{
    for(j=0;j<n;j++)
    {
        matrixobj.resultmatrix[i][j]=
       tempmatrixobj.matrix1[i][j]+tempmatrixobj.matrix2[i][j];
    }
}
return matrixobj;
//return tempmatrixobj;

// 返回 *this;

}

    void matrix::showmatrix()
     {
      for(i=0;i<m;i++)
      {
        for(j=0;j<n;j++)
        {
            cout<<resultmatrix[i][j]<<"\t";
        }
        cout<<"\n";
      }

   }

     int main()
     {
       matrix matrixobj1,matrixobj2;
        matrix resultmatrix;

       matrixobj1.getdata();

       matrixobj2.getdata();

    resultmatrix=matrixobj1+matrixobj2;

    resultmatrix.showmatrix();

    return 0;
  }

添加部分代码根本不起作用,它为每个矩阵取两次值,然后只输出一些内存地址。

输出:

输入矩阵 1 的行数:
3

输入矩阵 1 的列数:
3

输入矩阵 2 的行数:
3

输入矩阵 2 的列数:
3

可以添加矩阵

请提供matrix1:
1 1 1
1 1 1
1 1 1

请提供matrix2:
1 1 1
1 1 1
1 1 1

输入矩阵 1 的行数:
2

输入 matrix1 的列数:
2

输入矩阵 2 的行数:
2

输入矩阵 2 的列数:
2

可以添加矩阵

请提供matrix1:
1 1
1 1

请提供matrix2:
1 1
1 1
-1717986920 -1717986920
-1717986920 -1717986920
按任意键继续 。 . .

【问题讨论】:

标签: c++ matrix operator-overloading


【解决方案1】:

做加法的代码

matrixobj.resultmatrix[i][j]=tempmatrixobj.matrix1[i]   [j]+tempmatrixobj.matrix2[i][j];

将来自tempmatrixobj 的值,而不是来自参数的值添加到operator+

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-04-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多