运算符重载:"operator+"必须采用零个或一个参数

operator over loading: "operator+"must take either zero or one argument

本文关键字:零个 参数 一个 重载 operator+ 运算符      更新时间:2023-10-16

我有一个名为 IntMatrix 的矩阵类

namespace mtm
{
class IntMatrix
{
private:
int** data;
int col;
int row;
public:
IntMatrix(int row,int col,int num=0);
IntMatrix(const IntMatrix& mat);
//some functions
IntMatrix ::operator+(int num) const;
friend IntMatrix operator+(const int &num, const IntMatrix& matrix);
};
//ctor
IntMatrix::IntMatrix(int row,int col, int num) :data(new int*[row]), col(col), row(row)
{
for (int i = 0; i < col; i++)
{
data[i] = new int[col];
}
for (int i = 0; i < row; i++)
{
for (int j = 0; j < col); j++)
{
data[i][j] = num;
}
}
}
}

我正在尝试重载运算符+,以便这将起作用:

//copy ctor
IntMatrix::IntMatrix(const IntMatrix& mat)
{
data=new int*[mat.row];
for(int i = 0; i < mat.row; i++) 
{
data[i]=new int[mat.col];
}
row=mat.row;
col=mat.col;
for(int i=0;i<row;i++)
{
for(int j=0;j<col;j++)
{
data[i][j]=mat.data[i][j];
}
}
}
IntMatrix IntMatrix::operator+(int num) const
{
IntMatrix new_Matrix(*this);
for(int i=0;i<new_Matrix.row;i++)
{
for(int j=0;j<new_Matrix.col;j++)
{
new_Matrix.data[i][j]+=num;
}
}
return new_Matrix;
}
// the function I have problem with:
IntMatrix IntMatrix::operator+(const int &num, const IntMatrix& matrix) 
{
return matrix+num;
}
int main()
{
mtm::IntMatrix mat(2,1,3);
mtm::IntMatrix mat2=2+mat;
return 0;
}

无论我做什么,我都会不断收到此错误: 错误: 'mtm::IntMatrix mtm::IntMatrix::operator+(const int&, const mtm::IntMatrix&(' 必须采用零个或一个参数 IntMatrix IntMatrix::operator+(const int &num, const IntMatrix& matrix(

我试过了:

friend IntMatrix operator+(const int &num, const IntMatrix& matrix);
IntMatrix operator+(const int &num, const IntMatrix& matrix);
IntMatrix operator+(const int &num, const IntMatrix& matrix)const;
IntMatrix operator+(int &num, const IntMatrix& matrix);
IntMatrix operator+( int num, const IntMatrix& matrix);

然而我都遇到了同样的错误,所以有人知道正确的写法是什么吗?

使用friend声明函数不会使其成为类的一部分。int+IntMatrix 运算符不是IntMatrix::operator+- 它只是operator+

//        wrong - delete this part
//        vvvvvvvvvvv
IntMatrix IntMatrix::operator+(const int &num, const IntMatrix& matrix) 
{
return matrix+num;
}

我不知道您为向矩阵添加标量定义了什么,但想象一下一段时间类似的东西

IntMatrix IntMatrix::operator+(int k) const
{    
IntMatrix temp(this->x+k, this->y+k, this->z+k);
return temp;
}

所以有一个矢量 foo[0,1,2]你可以做:

IntMatrix r = foo + 2; 

和 r 将[2,3,4]