简体   繁体   中英

Custom object addition/subtraction

Hypothetical question. I have a custom object in my program, called GamePoint. It is properly defined and has all of its required members. What I'm wondering is if I can implement something similar to the following:

GamePoint p = new GamePoint(10, 10);
p += new GamePoint(15, 15);
//output: p = {25, 25}

Is there anyway to implement syntax like that?

Ofcourse you can, use operator overloading :

class GamePoint
{
    private int v1;
    private int v2;

    public GamePoint(int v1, int v2)
    {
        this.v1 = v1;
        this.v2 = v2;
    }

    public static GamePoint operator +(GamePoint a, GamePoint b)
    {
        return new GamePoint(a.v1 + b.v1, a.v2 + b.v2);
    }
}

Assuming your GamePoint class is what I guess it is here you go:

    class GamePoint
    {
        public int x { get; set; }
        public int y { get; set; }
        public GamePoint(int x_, int y_) {x=x_; y= y_;}
        public static GamePoint operator +(GamePoint GamePoint1, GamePoint GamePoint2)
        {
            return new GamePoint(
                GamePoint1.x + GamePoint2.x,
                GamePoint2.y + GamePoint1.y);
        }
        public override string ToString()
        {
            return " (" + this.x.ToString() + "/" + this.y.ToString() + ") ";
        }

    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM