gpt4 book ai didi

c# - 自定义对象加法/减法

转载 作者:太空宇宙 更新时间:2023-11-03 18:30:34 28 4
gpt4 key购买 nike

假设性问题。我的程序中有一个自定义对象,称为 GamePoint。它已正确定义并具有所有必需的成员。我想知道我是否可以实现类似于以下内容的东西:

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

有没有办法实现这样的语法?

最佳答案

当然可以,使用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);
}
}

关于c# - 自定义对象加法/减法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22925359/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com