overloading operator c# Vector

时间:2015-06-25 19:11:04

标签: c# vector operator-keyword

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?

4 个答案:

答案 0 :(得分:1)

You can only override an operator in its own class. Move all of that code to the Vector class.

答案 1 :(得分:1)

在向量类中,覆盖' - '运营商在其中

public class Vector
{
    public int X { get; set; }
    public int Y { get; set; }

    public static Vector operator -(Vector a, Vector b)
    {
        Vector v = new Vector();
        v.X = a.X - b.X;
        v.Y = a.Y - b.Y;
        return v;
    }
}

然后,您可以像那样使用它

Vector v1 = new Vector { X = 5, Y = 9};
Vector v2 = new Vector { X = 3, Y = 4 };
Vector vr = v1 - v2;
Console.WriteLine("Resultant Vector X: {0} & Y:{1}", vr.X, vr.Y);

我希望它会对你有所帮助。

答案 2 :(得分:1)

因为您正在尝试为类定义Operator。至少应将其中一个参数用于具有类的类型的运算符中。例如,你不能拥有类int并定义操作符仅获取 class VectorUtilv { private Point _p; private Point _p2; private Vector _v; public static VectorUtilv operator -(VectorUtilv a, VectorUtilv b) { //... } }

您不能覆盖现有类的运算符。只能是您自己的类。

如果你无法修改Vector Class,那么你应该声明一个名为Vector的类。或者使用您的类的类型作为运算符。

所以你可以拥有

    class Vecotr
    {
        private Point _p;
        private Point _p2;
        private Vector _v;
        public static Vecotr operator -(Vecotr a, Vecotr b)
        { 
            //...
        }
    }

System.Windows.Vector // is in Windows assembly
Vector // is your class

但是如果使用解决方案2.那么在使用Vector时需要使用限定符。

- name: Gathering facts
  setup:

答案 3 :(得分:0)

感谢您的回复。我希望在我弄清楚之前我会检查一下。本来可以节省我很多时间。我最后完全按照你们所说的那样做了。这就是我所拥有的。

public static VectorUtil operator - (VectorUtil aHeroPoint,VectorUtil bEnemyPoint){             VectorUtil v = new VectorUtil();             v.Vec = new Vector((aHeroPoint._p.X - bEnemyPoint._p.X),(aHeroPoint._p.Y - bEnemyPoint._p.Y));             返回v;  }