正如主题中所述,我遇到了将值从重载操作符传递回main函数的问题。我已经搜索了很多但没有效果。这是我的示例运算符。返回之前的行矩阵m我已经把cout检查算法是否正常工作。我在乘法运算符方面遇到了同样的问题。
matrix.h
class Matrix
{
public:
...
Matrix &operator+(const Matrix &m)
...
private:
int x;
int y;
double **tab;
};
matrix.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;
}
}
答案 0 :(得分:2)
基本问题是加法运算符不应返回引用,而应返回值:
Matrix operator+(const Matrix &m);
这适用于乘法,减法等。
除了返回对仅存在于函数范围内的变量的引用这一事实之外,返回引用在语义上没有意义。想想这个表达式:
B + C;
如果要返回引用,它应该引用什么?
一种常见的方法是将Matrix& operator+=(const Matrix&)
实现为成员运算符,然后将其作为非成员实现:
Matrix operator+(Matrix lhs, const Matrix& rhs)
{
return lhs += rhs;
}
这使得操作对称WRT LHS和RHS,允许双方进行隐式转换。
答案 1 :(得分:0)
简单回答:永远不会返回对您在函数中创建的对象的引用。这意味着,您的运算符应返回Matrix
,而不是Matrix&
(&
属于返回类型,您可能希望将其放在那里以使其更明显)。
如果为Matrix类提供了正确的移动构造函数,则返回结果时不会有昂贵的副本。