I have a matrix class called 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;
}
}
}
}
I am trying to overload operator+, so that this would work:
//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;
}
how ever no matter what I do I keep getting this error: error: ‘mtm::IntMatrix mtm::IntMatrix::operator+(const int&, const mtm::IntMatrix&)’ must take either zero or one argument IntMatrix IntMatrix::operator+(const int &num, const IntMatrix& matrix)
I tried:
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);
yet I got the same error with all of them, so does any one know what is the correct way to write it?
friend) compiles just right for me, provided that I add a body for that function (and fix typo in constructor) - Yksisarvinen