Let’s explain what operator overloading is all about with an example of a class that represents a date. Would it not be great if we could subtract two date objects and be returned an int representing the number of days elapsing between the two dates. We would like to use the good old subtraction operator – like we do when subtracting numbers. Also we would like the > operator to compare two date objects and tell us which one is larger. The + operator could add a number to a date resulting in a new date object. Thus, operator overloading lets us redefine the existing operators so that they work with classes/objects we create like yyy. We have not yet instructed C# on how to use the trusty old + operator with two yyy objects. Though C# knows how to use the + to add two numbers, it does not know how to add two yyy’s.
using System; using System.Collections.Generic; using System.Text;
namespace ConsoleApplication11 { class Distance { int m, cm; public Distance(int m, int cm) { this.m = m + cm/100; this.cm = cm %100; }
public void Show() { Console.WriteLine("{0} m {1} cm", m, cm); } public static bool operator <(Distance d1, Distance d2) { return (d1.m * 100 + d1.cm < d2.m * 100 + d2.cm); } public static bool operator >(Distance d1, Distance d2) { return (d1.m * 100 + d1.cm > d2.m * 100 + d2.cm); }
public static Distance operator +(Distance d1, Distance d2) { return new Distance(d1.m+d2.m,d1.cm+d2.cm); }
public static explicit operator int(Distance d) { return d.m * 100 + d.cm; } }
class Program { static void Main(string[] args) { Distance d1 = new Distance(3, 2); Distance d2 = new Distance(10, 205); Distance d3;
d3 = d1 + d2; if(d1<d2) d1.Show(); else d2.Show();
d3.Show();
int k = (int) d3;
Console.WriteLine(k);
} } }
|
No responses found. Be the first to respond and make money from revenue sharing program.
|