How to overload the * operator for your own class?

matrix.hpp
class Matrix
{
public:
 Matrix(int rows, int columns, const double* elems);
~Matrix();

 Matrix* operator*(Matrix& matrix);

 double det();
 Matrix* invert();
 Matrix* transpose();
};


matrix.cpp
Matrix* Matrix::operator*(Matrix& matrix)
{
//
}


main.cpp
int main(int argc, char** argv)
{
 double d[] = {1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0};

 Matrix* m = new Matrix(3, 3, d);

 Matrix* m1 = new Matrix(3, 3, d);

 Matrix* m2 = m * m1;

 return EXIT_SUCCESS;
}


Error text: main.cpp:16:5: error: invalid operands of types ‘Matrix*’ and ‘Matrix*’ to binary ‘operator*’
m * m1;


Thank you.
June 14th 19 at 21:03
2 answers
June 14th 19 at 21:05
Solution
You are trying to multiply pointers. Dereference it first.
Or make the operator a class member with the signature (Matrix*, Matrix*).
thx - Osborne.Dietri commented on June 14th 19 at 21:08
June 14th 19 at 21:07
Avoid using pointers where you can do without them. Plus, almost always pass parameters by const&.

class Matrix
{
public:
 Matrix(int rows, int columns, const double* elems);
~Matrix();

 Matrix operator*(const Matrix& matrix);

 double det();
 Matrix invert();
 Matrix transpose();
};


Matrix Matrix::operator*(const Matrix& matrix)
{
//
}


int main(int argc, char** argv)
{
 double d[] = {1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0};

 Matrix m(3, 3, d);

 Matrix m1(3, 3, d);

 Matrix m2 = m * m1;

 return EXIT_SUCCESS;
}

Find more questions by tags C++