1

C # Vector Overload Operator

 1 year ago
source link: https://www.codesd.com/item/c-vector-overload-operator.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

C # Vector Overload Operator

advertisements

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 Gets int.

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

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

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

But if you use solution 2. then you need to use qualifiers when using Vector.

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




About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK