15.02.2015 Views

C# 4 and .NET 4

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

operator overloading ❘ 169<br />

that we want people using your Vector to be able to write double X = a*b to calculate the inner product<br />

of two Vector objects (a <strong>and</strong> b). The relevant overload looks like this:<br />

public static double operator * (Vector lhs, Vector rhs)<br />

{<br />

return lhs.x * rhs.x + lhs.y * rhs.y + lhs.z * rhs.z;<br />

}<br />

Now that you underst<strong>and</strong> the arithmetic operators, you can check that they work using a simple<br />

test method:<br />

static void Main()<br />

{<br />

// stuff to demonstrate arithmetic operations<br />

Vector vect1, vect2, vect3;<br />

vect1 = new Vector(1.0, 1.5, 2.0);<br />

vect2 = new Vector(0.0, 0.0, -10.0);<br />

}<br />

vect3 = vect1 + vect2;<br />

Console.WriteLine("vect1 = " + vect1);<br />

Console.WriteLine("vect2 = " + vect2);<br />

Console.WriteLine("vect3 = vect1 + vect2 = " + vect3);<br />

Console.WriteLine("2*vect3 = " + 2*vect3);<br />

vect3 += vect2;<br />

Console.WriteLine("vect3+=vect2 gives " + vect3);<br />

vect3 = vect1*2;<br />

Console.WriteLine("Setting vect3=vect1*2 gives " + vect3);<br />

double dot = vect1*vect3;<br />

Console.WriteLine("vect1*vect3 = " + dot);<br />

Running this code (Vectors2.cs) produces the following result:<br />

Vectors2<br />

vect1 = ( 1, 1.5, 2 )<br />

vect2 = ( 0, 0, -10 )<br />

vect3 = vect1 + vect2 = ( 1, 1.5, -8 )<br />

2*vect3 = ( 2, 3, -16 )<br />

vect3+=vect2 gives ( 1, 1.5, -18 )<br />

Setting vect3=vect1*2 gives ( 2, 3, 4 )<br />

vect1*vect3 = 14.5<br />

This shows that the operator overloads have given the correct results, but if you look at the test code closely,<br />

you might be surprised to notice that it actually used an operator that wasn’t overloaded — the addition<br />

assignment operator, +=:<br />

vect3 += vect2;<br />

Console.WriteLine(“vect3 += vect2 gives “ + vect3);<br />

Although += normally counts as a single operator, it can be broken down into two steps: the addition<br />

<strong>and</strong> the assignment. Unlike the C++ language, <strong>C#</strong> will not actually allow you to overload the = operator,<br />

but if you overload +, the compiler will automatically use your overload of + to work out how to perform<br />

a += operation. The same principle works for all the assignment operators such as -=, *=, /=, &=,<br />

<strong>and</strong> so on.<br />

www.it-ebooks.info

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!