[英]implementing Matrix class addition operator overloading weird output
I'm trying to implement a matrix class and overloading the + and = operators. 我正在尝试实现矩阵类并重载+和=运算符。 The problem is I'm getting weird output when I add two matrices as in this picture. 问题是当我添加两个矩阵时,我得到了奇怪的输出,如图所示。 adding two matrices output console 添加两个矩阵输出控制台
#include <iostream>
#include <iomanip>
using namespace std;
class Matrix
{
int **p, m, n;
public:
Matrix(int row, int col)
{
m = row;
n = col;
p = new int*[m];
for (int i = 0; i < m; i++)
p[i] = new int[n];
}
Matrix (Matrix & x)
{
for(int i = 0; i < m; i++)
{
for(int j = 0; j < n; j++)
{
p[i][j]=x.p[i][j];
}
}
}
~Matrix()
{
for (int i = 0; i < m; i++)
delete [] p[i];
delete [] p;
}
void accept()
{
for(int i = 0; i < m; i++)
{
for(int j = 0; j < n; j++)
{
cin >> p[i][j];
}
}
}
void display()
{
for(int i = 0; i < m; i++)
{
for(int j = 0; j < n; j++)
{
cout << setw(10)<<left <<p[i][j] <<" | ";
}
cout << "\n--------------------------------------"<<endl;
}
}
Matrix& operator +(const Matrix & m2)
{
Matrix r(m, n);
for(int i = 0; i < m; i++)
{
for(int j = 0; j < n; j++)
{
r.p[i][j] = p[i][j] + m2.p[i][j];
}
}
return r;
}
Matrix& operator= (const Matrix & eq)
{
for(int i = 0; i < m; i++)
{
for(int j = 0; j < n; j++)
{
p[i][j]=eq.p[i][j];
}
}
return *this;
}
friend Matrix operator * (Matrix, Matrix);
};
Matrix operator* (Matrix a , Matrix b)
{
Matrix B(1,1);
if(a.n == b.m)
{
Matrix T(a.m, b.n);
for(int i = 0; i < a.m; i++)
{
for(int k = 0; k < b.n; k++)
{
T.p[i][k] = 0;
for(int j = 0; j < a.n; j++)
{
T.p[i][k]+= a.p[i][j] * b.p[j][k];
}
}
}
B = T;
}
return B;
}
int main()
{
cout << "Enter Matrix 1 (3x2):"<<endl;
Matrix m1(3,2);
m1.accept();
m1.display();
cout << "Enter Matrix 2 (3x2):"<<endl;
Matrix m2(3,2);
m2.accept();
m2.display();
Matrix m3(3,2);
m3=m1+m2;
cout <<endl<< "matrix1 + matix2 is:\n "<<endl;
m3.display();
}
Any ideas how to fix that? 任何想法如何解决? I would be grateful for your help and advices with improving it because probably there will be some mistakes. 感谢您提供的改进建议和帮助,因为可能会出现一些错误。 I use CodeBlocks IDE. 我使用CodeBlocks IDE。
The problem is that your operator +
returns a local variable Matrix
as a reference ; 问题是您的operator +
返回了局部变量Matrix
作为参考 ; this is undefined behavior . 这是未定义的行为 。 It should be returned by value, not by reference. 它应该按值而不是引用返回。
Make sure that your Matrix
class has a copy constructor that takes a const
input, ie 确保您的Matrix
类具有一个采用const
输入的复制构造const
,即
Matrix (const Matrix & x)
and that it initializes the array before writing into it. 并且它会在写入数组之前初始化数组。 Move the initialization code (the two loops with allocation) into a separate private function, and call it from the default constructor and from the copy constructor. 将初始化代码(带有分配的两个循环)移到单独的私有函数中,然后从默认构造函数和复制构造函数中调用它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.