假设性问题。我的程序中有一个名为GamePoint的自定义对象。它已正确定义并具有所有必需成员。我想知道的是,我是否可以实现类似于以下内容:
GamePoint p = new GamePoint(10, 10);
p += new GamePoint(15, 15);
//output: p = {25, 25}
无论如何都要实现这样的语法吗?
答案 0 :(得分:7)
你可以使用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);
}
}
答案 1 :(得分:0)
假设你的GamePoint课程是我想的,你就去了:
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() + ") ";
}
}