我有一个名为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;
}
我不知道你定义了什么来给矩阵添加一个escalar,但是想象一下
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]