Jump to content
Xtreme .Net Talk

Recommended Posts

Posted

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.

  • *Experts*
Posted

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

"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

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...