假设我创建了一个简单的类。

class Zoo {
  public int lionCount;
  public int cheetahCount;
  Zoo(lions, cheetahs) {
    lionCount = lions;
    cheetahCount = cheetahs;
  }
}

现在假设我有两个动物园。
Zoo zoo1 = new Zoo(1,2);
Zoo zoo2 = new Zoo(3,5);

是否可以为此类定义算术运算,以便…
Zoo zoo3 = zoo1 + zoo2; //makes a zoo with 4 lions and 7 cheetahs
Zoo zoo4 = zoo1 * zoo2; // makes a zoo with 3 lions and 10 cheetahs

换句话说,我如何定义C类的自定义算术运算?

最佳答案

当然可以使用运算符重载

class Zoo
{
  public int lionCount;
  public int cheetahCount;

  Zoo(int lions, int cheetahs)
  {
    lionCount = lions;
    cheetahCount = cheetahs;
  }

  public static Zoo operator +(Zoo z1, Zoo z2)
  {
    return new Zoo(z1.lionCount + z2.lionCount, z1.cheetahCount + z2.cheetahCount);
  }
}

其他运算符的处理方式几乎相同;-)
有关它的更多信息,请检查https://msdn.microsoft.com/en-us/library/aa288467(v=vs.71).aspx

10-02 02:00
查看更多