【问题标题】:Sum of matrices in C++ using operator overloading(C++)使用运算符重载的 C++ 中的矩阵求和(C++)
【发布时间】:2019-03-01 16:34:38
【问题描述】:

我有这段代码,用于使用重载的“+”运算符添加两个矩阵。但是我的程序有一些错误。但我无法找到其中任何一个。我应该从用户那里得到两个矩阵,然后通过使用 C++ 的重载特性来显示这两个矩阵的总和。我从用户那里获取输入并单独显示每个矩阵都没有问题。但是一旦调用重载函数,代码就会失败。我不知道实际上在哪里。

#include <iostream>
using namespace std;
class matrix
{
    int r=0,c=0,i=0,j=0,e[10][10];
public:
    matrix getMatrix()
    {
        cout<<"Enter the no. of rows of matrix:"<<endl;
        cin>>r;
        cout<<"Enter the no. of columns of matrix:"<<endl;
        cin>>c;
        cout<<"Enter the elements of the matrix:"<<endl;
        for(i=0;i<r;i++)
        {
            for (j=0;j<c;j++)
            {
                cin>>e[i][j];
            }
        }
    }
    matrix operator +(matrix m)
    {
        matrix sumMatrix;
        for(i=0; i<r; i++)
        {
            for (j=0; j<c; j++)
            {
                sumMatrix.e[i][j]=this->e[i][j]+m.e[i][j];
            }
        }
        return sumMatrix;
    }
    void displayMatrix()
    {
        for(i=0; i<r; i++)
        {
            cout<<endl;
            for (j=0; j<c; j++)
            {
                cout<<this->e[i][j]<<"    ";
            }
        }
    }
};
int main()
{
    cout<<"NOTE: In order to add matrices, they must have same dimension."<<endl;
    matrix m1,m2,m3;
    cout<<"1st matrix:"<<endl;
    m1.getMatrix();
    m1.displayMatrix();cout<<endl;
    cout<<"2nt matrix:"<<endl;
    m2.getMatrix();
    m2.displayMatrix();cout<<endl;
    m3=m1+m2;
    cout<<"The sum of the two matrices is:"<<endl;
    m3.displayMatrix();
    return 0;
}

我的输出 here.

【问题讨论】:

    标签: c++ matrix operator-overloading


    【解决方案1】:

    您的错误是您没有在operator+函数中设置返回对象的rc的值。

    matrix operator +(matrix m)
    {
        matrix sumMatrix;
        sumMatrix.r = this->r;
        sumMatrix.c = this->c;
    
        for(i=0; i<r; i++)
        {
            for (j=0; j<c; j++)
            {
                sumMatrix.e[i][j]=this->e[i][j]+m.e[i][j];
            }
        }
        return sumMatrix;
    }
    

    编译器还期望getMatrix() 返回矩阵。 改变你的

    matrix getMatrix() {...}
    

    to(也重命名)

    void readFromConsole() {...}
    

    【讨论】:

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