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.

166 ❘ ChaPTer 7 OperAtOrs And cAsts<br />

The fact that this example will be developed as a struct rather than a class is not<br />

signifi cant. Operator overloading works in the same way for both structs <strong>and</strong> classes.<br />

The following is the defi nition for Vector — containing the member fi elds, constructors, a ToString()<br />

override so you can easily view the contents of a Vector , <strong>and</strong>, fi nally, that operator overload:<br />

namespace Wrox.ProCSharp.OOCSharp<br />

{<br />

struct Vector<br />

{<br />

public double x, y, z;<br />

public Vector(double x, double y, double z)<br />

{<br />

this.x = x;<br />

this.y = y;<br />

this.z = z;<br />

}<br />

public Vector(Vector rhs)<br />

{<br />

x = rhs.x;<br />

y = rhs.y;<br />

z = rhs.z;<br />

}<br />

public override string ToString()<br />

{<br />

return "( " + x + ", " + y + ", " + z + " )";<br />

}<br />

code download VectorStruct solution<br />

This example has two constructors that require the initial value of the vector to be specifi ed, either by<br />

passing in the values of each component or by supplying another Vector whose value can be copied.<br />

Constructors like the second one that takes a single Vector argument are often termed copy constructors<br />

because they effectively allow you to initialize a class or struct instance by copying another instance. Note<br />

that to keep things simple, the fi elds are left as public . We could have made them private <strong>and</strong> written<br />

corresponding properties to access them, but it would not have made any difference to the example, other<br />

than to make the code longer.<br />

Here is the interesting part of the Vector struct — the operator overload that provides support for the<br />

addition operator:<br />

}<br />

}<br />

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

{<br />

Vector result = new Vector(lhs);<br />

result.x += rhs.x;<br />

result.y += rhs.y;<br />

result.z += rhs.z;<br />

}<br />

return result;<br />

The operator overload is declared in much the same way as a method, except that the operator keyword<br />

tells the compiler it is actually an operator overload you are defi ning. The operator keyword is followed<br />

by the actual symbol for the relevant operator, in this case the addition operator ( + ). The return type is<br />

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!