Operators Overloading
- C
- C++
- C#
- Java
- Rust
- Go
- Javascript
- Typescript
- Python
// No Native Support.
// Use named functions instead.
typedef struct Vector2
{
float x;
float y;
} Vector2;
Vector2 add(Vector2 first, Vector2 second)
{
return (Vector2) {
.x = first.x + second.x,
.y = first.y + second.y
};
}
class Vector2
{
public:
float x;
float y;
Vector2 operator+(Vector2 const& other) const
{
return Vector2 { x + other.x, y + other.y };
}
bool operator==(Vector2 const& other) const
{
return x == other.x && y == other.y;
}
};
Vector2 result = first + second;
public struct Vector2
{
public float X { get; }
public float Y { get; }
public Vector2(float x, float y)
{
X = x;
Y = y;
}
public static Vector2 operator +(Vector2 first, Vector2 second)
{
return new Vector2(first.X + second.X, first.Y + second.Y);
}
}
Vector2 result = first + second;
// No Native Support.
// Use named methods instead.
record Vector2(float x, float y) {
public Vector2 add(Vector2 other) {
return new Vector2(x + other.x, y + other.y);
}
}
Vector2 result = first.add(second);
use std::ops::Add;
struct Vector2 {
x: f32,
y: f32,
}
impl Add for Vector2 {
type Output = Vector2;
fn add(self, other: Vector2) -> Vector2 {
Vector2 {
x: self.x + other.x,
y: self.y + other.y,
}
}
}
let result = first + second;
// No Native Support.
// Use named methods or functions instead.
type Vector2 struct {
X float64
Y float64
}
func (first Vector2) Add(second Vector2) Vector2 {
return Vector2{
X: first.X + second.X,
Y: first.Y + second.Y,
}
}
result := first.Add(second)
// No Native Support for custom operator overloading.
// Use named methods instead.
class Vector2 {
constructor(x, y) {
this.x = x;
this.y = y;
}
add(other) {
return new Vector2(this.x + other.x, this.y + other.y);
}
}
const result = first.add(second);
// No Native Support for custom operator overloading.
// Use named methods instead.
class Vector2 {
public constructor(
public readonly x: number,
public readonly y: number,
) {}
public add(other: Vector2): Vector2 {
return new Vector2(this.x + other.x, this.y + other.y);
}
}
const result = first.add(second);
class Vector2:
def __init__(self, x: float, y: float) -> None:
self.x = x
self.y = y
def __add__(self, other: "Vector2") -> "Vector2":
return Vector2(self.x + other.x, self.y + other.y)
def __eq__(self, other: object) -> bool:
if not isinstance(other, Vector2):
return False
return self.x == other.x and self.y == other.y
result = first + second