views:

103

answers:

2

I have noticed that it is possible to define a custom class and then use operators like +,-,/ and * on a number of them rather than using methods to do so. For example, I created a Matrix class that does complex matrix algebra/differentiation and created it so that all the operations were controlled by methods:

Matrix m1 = new Matrix(new double[][] { /* Some data */ });
Matrix m2 = new Matrix(new double[][] { /* Some other data */ });

// Returns a new Matrix object equal to the result
m1 = m1.Multiply(m2);
m1 = m1.Add(m2.Inverse);
m1 = m1.Subtract(m2.Determinant);
m1 = m1.ApplyToCombinator(new AlgebraMatrix(new string[][] { /* Some data *. }));

However, after looking at This CodeProject Page, and after using the XNA framework (Position = Speed * (float)gameTime.ElapsedTime.TotalSeconds; where a Vector2 object is being multiplied by a float using *), you can use the +,-,/ and * instead.

So how would I have to change my class so I could simply type the following code to do the same as above?

m1 = m1 * m2 + m2.Inverse - m2.Determinant;

Thanks in advance.

+10  A: 

MSDN: Operator overloading

public static Matrix operator +(Matrix mat)
{
    //do stuff  
}
Francis B.
Thanks, I had no idea what it was called!
Callum Rogers
+2  A: 

Sounds like you need to look at Operator Overloading. Also see this tutorial. Have fun :)

Dan Diplo
Nice tutorial, thanks. Everyone seems to be using matrices for some reason...
Callum Rogers