【发布时间】:2013-04-03 08:36:57
【问题描述】:
如主题中所述,我遇到了将值从重载运算符传递回主函数的问题。我已经搜索了很多但没有效果。这是我的示例运算符。返回 Matrix m 之前的行,我已将 cout 用于检查算法是否正常工作。乘法运算符也有同样的问题。
矩阵.h
class Matrix
{
public:
...
Matrix &operator+(const Matrix &m)
...
private:
int x;
int y;
double **tab;
};
矩阵.cpp
Matrix &Matrix::operator+(const Matrix &m)
{
if(x==m.x && y==m.y)
{
Matrix temp(x,y);
for(int i=0;i<x;i++)
{
for(int j=0;j<y;j++)
{
temp.tab[i][j]=tab[i][j]+m.tab[i][j];
}
}
cout << temp<< endl;
return temp;
}
else
{
char er[]={"error!\n"};
throw er;
}
}
【问题讨论】:
-
您正在返回对局部变量的引用(
temp,对 :-)。当你返回 main 时,它已经被销毁了。而是按值返回。 -
@juanchopanza 谢谢你的帮助 你是对的!我在复制构造函数中犯了一个愚蠢的错误,这就是为什么无论将什么复制到主函数,结果我的矩阵都填充了 0。