Skip to content

Operator overload in different languages

xushiwei edited this page Aug 7, 2021 · 2 revisions

C++

class Foo {
public:
  static Foo operator+(Foo a, Foo b) {
    ...
  }
  static Foo operator-(Foo a) {
    ...
  }
}

C#

public class Foo {
  public static Foo operator+(Foo a, Foo b) {
    ...
  }
  public static Foo operator-(Foo a) {
    ...
  }
}

Kotlin

class Foo {
  operator fun plus(other Foo): Foo {
    ...
  }
  operator fun unaryMinus(): Foo {
    ...
  }
}

Python

class Foo:
  def __add__(self, other):
    ...

Go+

type Foo struct {...}

func (a Foo) + (b Foo) Foo {
  ...
}

func -(a Foo) Foo {
  ...
}