如主题中所述,我在将值从重载运算符传递回主函数时遇到了问题。我已经搜索了很多但没有效果。这是我的示例运算符。返回 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;
}
最佳答案
根本问题是加法运算符不应该返回一个引用,而是一个值:
Matrix operator+(const Matrix &m);
这适用于乘法、减法等。
除了返回对仅存在于函数范围内的变量的引用这一事实之外,返回引用在语义上没有任何意义。想想这个表达式:
B + C;
如果要返回一个引用,它应该引用什么?
一种常见的做法是将Matrix& operator+=(const Matrix&)
实现为成员运算符,然后将加法实现为非成员:
Matrix operator+(Matrix lhs, const Matrix& rhs)
{
return lhs += rhs;
}
这使得操作对称 WRT LHS 和 RHS,允许在两侧进行隐式转换。
关于c++ - 无法从重载运算符传递值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15782496/