【发布时间】:2020-10-15 23:18:30
【问题描述】:
我有一个名为 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;
}
}
}
}
我正在尝试重载 operator+,以便它可以工作:
//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& 矩阵)
我试过了:
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);
但是我都遇到了同样的错误,所以有人知道正确的写法是什么吗?
【问题讨论】:
-
@molbdnilo 这是一个可重复的示例,我发布了类、ctor、我遇到问题的函数以及 main()
-
你确定你从你发布的代码中得到了那个错误吗?
-
您当前的示例(使用
friend)对我来说正好编译,前提是我为该函数添加了一个主体(并修复了构造函数中的错字) -
好的,我会将主体添加到该函数中
-
您发布的内容足以编译它,但它没有重现错误:godbolt.org/z/Lqd5xL
标签: c++ matrix operator-overloading