Morpheus Posted February 1, 2003 Posted February 1, 2003 I'm having some problem understanding operator overloading. I need to overload == to compare if two points have the same coordinates. Two objects Point1 and Point2 and they have both got two coordinates(X and Y). I would be really glad if someone could explain two me what I have to do and why. Quote
*Experts* Nerseus Posted February 1, 2003 *Experts* Posted February 1, 2003 If you use the built in type Point (part of System.Drawing) you won't have to overload - they work as expected. If you just want to see how to implement operator overloading, here's a sample: struct MyStruct { public int x; public int y; public MyStruct(int x, int y) { this.x = x; this.y = y; } public static bool operator ==(MyStruct v1, MyStruct v2) { return (v1.x==v2.x && v1.y==v2.y); } public static bool operator !=(MyStruct v1, MyStruct v2) { return (v1.x!=v2.x || v1.y!=v2.y); } } And here's the sample code to test: MyStruct m1 = new MyStruct(1, 2); MyStruct m2 = new MyStruct(3, 4); MyStruct m3 = new MyStruct(1, 2); // The following is true; if(m1 == m3) Debug.WriteLine("="); // The following is not true if(m1 == m2) Debug.WriteLine("="); -nerseus Quote "I want to stand as close to the edge as I can without going over. Out on the edge you see all the kinds of things you can't see from the center." - Kurt Vonnegut
Morpheus Posted February 1, 2003 Author Posted February 1, 2003 Why do you use struct? Can I use have a class instead of struct? Quote
*Experts* Volte Posted February 1, 2003 *Experts* Posted February 1, 2003 You can use a class if you want; operator overloading will work in either. Quote
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.