Operator overloading

Morpheus

Regular
Joined
Jan 18, 2002
Messages
62
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.
 
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:
C#:
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:
C#:
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
 
Back
Top