【发布时间】: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