So, I am trying to override the "-" operator in c# to be able to subtract 2 vectors, but my class cannot implement Vector.
namespace Vectors
{
class VectorUtilv
{
private Point _p;
private Point _p2;
private Vector _v;
public Vector V
{
get { return _v; }
set { _v = value; }
}
public Point AddVector(Vector v)
{
_p.X = (_p.X + v.X);
_p2.Y = (_p.Y + v.Y);
return _p2;
}
// This is where I am trying to override but I cant add the v.X or
// the v.Y because it is not a vector. If i cast it as a vector the
// override doesn't work.
//////////////////////////////////////////////////////////////////
public static VectorUtilv operator -(Vector a, Vector b)
{
Vector v = new Vector();
v.X = a.X - b.X;
v.Y = a.Y - b.Y;
return v;
}
}
}
Any idea how I can remedy this issue?
Because you are Trying to define Operator for Class. At least one of its Parameters should be used in Operator with Type of your Class. for example you cant have class
Car
and define Operator witch only Getsint
.You can't override the operator for existing classes.only your own classes.
If you cant Modify Vector Class then you should declare your own class named Vector. or use the Type of your class for operator.
so you can have
or
But if you use solution 2. then you need to use qualifiers when using Vector.