Overload * Operator: Both Directions?

Nov 24, 2010 at 5:12am
Hey all.

I've overloaded the multiplication operator in my Matrix class (for scalar multiplication):

 
Matrix<T> operator*(double scalar); //Scale matrix 


So if I have:

1
2
3
4
5
Matrix a;
double b;

a*b - Works
b*a - Error


How can I make both work?

Thanks,

Nick.

Nov 24, 2010 at 6:39am
Use both:

1
2
Matrix<T> operator*(double scalar);
double operator*(const Matrix<T>& matrix);


Usually having commutativity by default on an operator would be undesirable, not to mention hard to implement in an intuitive way for a language, so you have to define both.
Nov 24, 2010 at 10:55pm
Ok kool. But the operation would return a Matrix:

double operator*(const Matrix<T>& matrix);

Would return a double?

Any tips?

Thanks.
Nov 24, 2010 at 11:23pm
Whoops, yea, that's not the way it should be.

You'd need to use a global operator for one of the two cases, but it's easy enough to map that global operator on the existing one for the commutative case:

1
2
3
4
5
6
7
class Matrix {
operator*(double);
};

Matrix operator*(double, Matrix) {
return Matrix*double;
}
Nov 25, 2010 at 2:06am
You have to give argument values names to use them.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
struct Matrix
{
  // This is the (Matrix * scalar) operator
  Matrix operator * ( double k ) const
  {
    Matrix m;
    /* multiply your matrix (*this) by the scalar (k) here and put the result in m*/
    return m;
  }
};

// This is the (scalar * Matrix) operator
Matrix operator * ( double k, const Matrix& m )
{
  return m * k;
}

Hope this helps.
Topic archived. No new replies allowed.