views:

289

answers:

8

I'm studying ICT. One of my courses is C# and another is Physics. Our Physics teacher used Visual Studio to animate some movements gave us some of the code he used to do it. He told us to look it up. Here's something I don't recognize:

public static Vector operator + (Vector v1, Vector v2)
{
    return new Vector(v1.X + v2.X, v1.Y + v2.Y, v1.Z + v2.Z);
}

That is supposed to be a constructor, but I've never seen anything like it before. I don't know what it's called, so I don't know what to google for.

Can someone enlighten me please?

+3  A: 

He's overloading the "+" operator for the Vector class. See here for more information on the topic.

Alex Fort
+10  A: 

That is called "operator overloading". It is not a constructor but returns a new Vector.

See: Operator Overloading

Leonidas
+3  A: 

That's overloading the '+' operator for the Vector class so whenever you do 'v1 + v2' that code gets executed.

axel_c
+2  A: 

This isn't a constructor but an operator overload for + This is how you overload the behaviour for:

Vector a = new Vector();
Vector b = new Vector();
Vector c = a + b;

More info at the MSDN article.

Ray Booysen
+4  A: 

It's not a constructor. It's an operator method for the '+' operator. It defines what happens when you do somethig like the following:-

var Vector v1 = new Vector(1,2,3);
var Vector v2 = new Vector(1,2,3);
var Vector v3 = v1 + v2;
AdamRalph
somehow I knew I'd never get the first answer in for this one, it was always going to get bombarded ;-)
AdamRalph
A: 

The Line:

public static Vector operator + (Vector v1, Vector v2)

...is not a constructor. It's simply overloading the + (Plus) operator for the parent class. I assume the parent class is a refined vector class?

The line:

return new Vector(v1.X + v2.X, v1.Y + v2.Y, v1.Z + v2.Z);

...Is using the constructor of the Vector class to pass three arguments (X, Y, and Z it looks like)

Robert Venables
A: 

It is overloaded + operator. All OOP languages (except Java perhaps, need to check reference) allow operator overloading.

Tanveer Badar
A: 

He is indeed overloading the + operator.

what does this mean? well it's simple:

if you have this:

int i = 10;
int j = 20;
int x = i + j;

In this example x would be 30 because C# knows if we are using integers and use + that we need to take the sum.

But now you are working with Vectors. A 3dimensional vector has 3 values: X, Y and Z. If you want the sum of 2 vectors well how do you work? does it go like

v1.X + v2.Y and v1.Y + v2.Z and v1.Z + v2.X  

or should C# do it like this:

v1.X + v1.Y and v1.Z + v2.X and v2.Y + v2.Z

With operator overloading you define how the + operator should be implemented when using Vectors. In our case it's:

v1.X + v2.X and v1.Y + v2.Y and v1.Z + v2.Z 

not that hard ;)

juFo