我知道在Java和C#中没有像运算符重载这样的东西。我的老师交给我一项任务,以实现这些语言中的任何一种的运算符重载。我不知道这些语言的深层概念,只知道基本的OOP。那么谁能说出还有其他方法可以实现这一目标吗?
在 C# 中有一个叫做运算符重载的东西,请查看 MSDN 中的以下代码片段:
public struct Complex
{
public int real;
public int imaginary;
public Complex(int real, int imaginary)
{
this.real = real;
this.imaginary = imaginary;
}
// Declare which operator to overload (+), the types
// that can be added (two Complex objects), and the
// return type (Complex):
public static Complex operator +(Complex c1, Complex c2)
{
return new Complex(c1.real + c2.real, c1.imaginary + c2.imaginary);
}
}
可重载运算符的完整列表
正如 des 所显示的,C# 确实有运算符重载。另一方面,Java则没有。Java比较两个对象相等的方式是通过覆盖方法equals(Object)
来完成的,该方法继承自基对象java.lang.Object
。下面是一个用法示例:
public class MyClass {
private int value;
@Override
public boolean equals(Object o) {
return o instanceof MyClass && ((MyClass)o).value == this.value;
}
}
当然,这只是复制重载==
运算符的解决方法。对于其他运算符,例如>=
或<=
则没有任何内容。但是,您可以使用 OO 通过通用接口重新创建它:
interface Overloadable<T> {
public boolean isGreaterThan(T other);
public boolean isLessThan(T other);
}
public class MyClass implements Overloadable<MyClass> {
private int value;
@Override
public boolean equals(Object o) {
return o instanceof MyClass && ((MyClass)o).value == this.value;
}
@Override
public boolean isGreaterThan(MyClass other) {
return this.value > other.value;
}
@Override
public boolean isLessThan(MyClass other) {
return this.value < other.value;
}
}
这绝不是真正的运算符重载,因为您没有使运算符重载。但是,它确实提供了以相同方式比较对象的能力。